Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$ is not a function error after AJAX call

Tags:

jquery

ajax

I'm adding infinite scrolling to a WordPress webpage. I'm using jQuery to add a class to every third content item with the following code without any problems:

jQuery(document).ready(function($) {
    $(".leden li:nth-child(3n)").addClass('last');
});

After finding out that the above code wasn't executed after the AJAX call to show the dynamic content I've added the following code:

jQuery(document).ajaxComplete(function($) {
    $(".leden li:nth-child(3n)").addClass('last');  
});

I'm not really sure if this is the correct way to add a class with jQuery after the AJAX but it seems like it as Firebug only shows the following console error after scrolling down the page and dynamically loading the content:

TypeError: $ is not a function

This confuses me as a novice JavaScript/jQuery user because why is the error only shown for the second piece of jQuery when it uses the same format? I'm only using a different even handler as far as I know...

What am I doing wrong and also, is this the correct way to execute jQuery when using AJAX to dynamically adding content?

like image 911
NielsPilon Avatar asked May 21 '26 02:05

NielsPilon


1 Answers

When you do this :

jQuery(document).ajaxComplete(function($) {

you declare a variable $ in the scope of the function, shadowing the external declaration jQuery). As you pass no argument to the function this variable has value undefined.

Just do

jQuery(document).ajaxComplete(function() {

If you want to alias jQuery as $, put your whole code in a function call like this :

(function($){
   $(document).ajaxComplete(function() {
      $(".leden li:nth-child(3n)").addClass('last');  
   });
   // the rest of your code using $ goes here
})(jQuery);
like image 143
Denys Séguret Avatar answered May 22 '26 15:05

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!