Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

The Codex promotes this method of using $ inside a plugin/theme JavaScript file:

jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

But if you do that you only have access to $ inside ready(). I think functions should be broken into small modules which are called from ready(), not all lumped together inside ready(), so if I use the Codex's method then I have to pass $ to each function, which is annoying and crude. Writing out jQuery all the time instead of just using $ is also annoying.

I can just do $ = jQuery.noConflict(); at the start of my JavaScript file and then $ is available everywhere, but I suspect that that might cause problems with other plugins/themes in some situations. My searches haven't turned up any thorough explanations or definitive answers. Does anyone have any thoughts?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

You don't need $ = jQuery.noConflict();

Just wrap any functions outside document.ready() within:

(function($){  
  // use $ here safely
})(jQuery);
share|improve this answer
    
Yeah, that might work. Is there any reason to not wrap .ready() inside it too? –  Ian Dunn Jun 25 '11 at 15:29
    
Also, because it creates a closure, would it remain in memory until the page is closed? –  Ian Dunn Jun 25 '11 at 15:45
1  
Well you can wrap the ready function too, but there's no point to do that because you'll still need to tell jQuery to run the function. So you will end up calling jQuery.something() anyway... I don't know about the memory usage, but I think that any function stays in memory until page changes in browser. –  onetrickpony Jun 25 '11 at 17:03
    
Not sure I follow you. If it's inside the wrapper then I can do $(document).ready( bgmp.init ); instead of jQuery(document).ready( bgmp.init );, which was the whole goal. I tried it out and it's working, so I'll put off the memory issue until later. Thanks for the help :) –  Ian Dunn Jun 25 '11 at 20:20
    
The goal was to use $ instead of jQuery only in one place from your entire script? I don't understand, do you have multiple $.ready() functions or...? –  onetrickpony Jun 25 '11 at 20:39
show 6 more comments

hope this answer can help somebody

put this code :

 $ = jQuery.noConflict(true);

before :

 $(document).ready(function($){ ... });
share|improve this answer
1  
The OP mentions in his question that he has reservations about this method as it might conflict with other plug-ins. –  Stephen Harris Aug 13 '12 at 13:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.