JQuery (document) .ready and passing '$'
I have a js file that I include in my Wordpress template. Is there a way to access the $ function inside my MediaBrowser object without having to clumsyly pass it as an argument?
Thanks Steve
var MediaBrowser = { initialize:function($){ $("a[rel^='mediaBrowser']").prettyPhoto(); } }; jQuery(document).ready(function($){ MediaBrowser.initialize($); }); +4
4 answers
Use the self-start function to access jQuery through $. There are many reasons why you would like to do this, so don't listen to other people telling you to simply access it around the world ...
var MediaBrowser = (function($) { return { initialize:function(){ $("a[rel^='mediaBrowser']").prettyPhoto(); } }; }(jQuery)); +3
I assume that you have any conflicts somewhere? You can create a closure for MediaBrowser. Keep in mind that this will need to be done after loading jQuery.
var MediaBrowser = function() { var $ = jQuery; return { init : function() { // blah jquery stuff using $(..) syntax } ... } }(); +1
An anonymous function can always be completed (but then, due to visibility, you will need to make the MediaBrowser part of the window explicate:
(function($){ window.MediaBrowser = { initialize: function(){ $('<p>').text('Sample').appendTo('body'); } }; })(jQuery); jQuery(document).ready(function(){ MediaBrowser.initialize(); }); 0