tags:

views:

27

answers:

3

I'm sure this is a simple question, just can't seem to get it to work right.

I was having some conflicts with jQuery, so I used the aliasing feature mentioned in the official documentation.

jQuery(document).ready(function($){
  $('.loadmore').addClass('hidden'); // works fine!

  loadmore();

});

function loadmore(){
  $('.loadmore').addClass('hidden'); // doesn't work!
}

How do I get the aliasing to work for my code that I threw into functions for better organization and for the ability to reuse? I'm currently using jQuery instead of $ for everything due to the issue presented in the sample above. Thought I could save a few bits of data and use the alias that's shown in all the tutorials.

+1  A: 

You can try this...

(function($) {

// Put all your jQuery here... and you can use $

})(jQuery);
alex
A: 

In this case, you could pass $ to your function.

jQuery(document).ready(function($){
    $('.loadmore').addClass('hidden'); // works fine!

    loadmore($);

});

function loadmore($){
    $('.loadmore').addClass('hidden'); // should work fine too!
}
cHao
first off, thanks! But one question, will I still be able to pass additional variables through? For instance, `loadmore($, num);` and receive it like this `function loadmore($, num) { }`
Sahas Katta
@Sahas Katta Yes.
alex
A: 

jQuery no conflict mode essentially sets the $ function to a different name, like so:

$('select something').doSomethingElse(); // Works
var $j = jQuery.noConfilct();
$('select something').doSomethingElse(); // Doesn't work
$j('select something').doSomethingElse(); // Works

If you don't want to use a name other than $ for jQuery you can do this:

(function ($) {
    $('selector').doSomething();
    $('another selector').doSomethingElse();
}(jQuery));

This makes jQuery = $, but only inside of the parenthesis, allows you work as usual, and never causes conflicts.

indieinvader
Nice! I like the idea of the first option better. One question though. Do I just declare the `var $j = jQuery.noConfilct();` before my document ready function and I'll be good to use `$j` anywhere in that JS file?
Sahas Katta
@Sahas Katta Yes. :)
alex