user1912899
user1912899

Reputation:

no jQuery on inserted HTML

I have jQuery loaded in the head of my page, to do something on click of elements with a certain class.

$(function(){
  $(".addtocal").click(function(){
  $(this).next('.addToCalOptions').fadeIn('fast');
  return false;
  }
);
});

It works for all the .addtocal elements already present on the page. But not with a bunch of similar elements inserted in the page later by a jQuery .load function.

Now I'm pretty sure I have to use a "a delegated-events approachth" with the .on() function. Right?

This doesn't work, though:

$(function(){
  $("a").on("click", ".addtocal", function(){
  $(this).next('.addToCalOptions').fadeIn('fast');
  }
);
});

I'm lost. Any thoughts? Thanks!

Upvotes: 0

Views: 65

Answers (4)

Chamika Sandamal
Chamika Sandamal

Reputation: 24312

You have to use jQuery on syntax correctly. and for the on API, you dont need to add ready event since it is only fire once you clicked the items

$(document).on("click", ".addtocal", function(){
    $(this).next('.addToCalOptions').fadeIn('fast');
}

Upvotes: 0

PSL
PSL

Reputation: 123739

try this first with document, if this does work, probably a is not the container for .addtocal which already exists in DOM. You can then scale down document to a container that already exists in DOM.

$(function(){
  $(document).on("click", ".addtocal", function(){
  $(this).next('.addToCalOptions').fadeIn('fast');
  }
);

and if you identify the container you can write it as:-

 $(function(){
      $("containerSelector").on("click", ".addtocal", function(){
      $(this).next('.addToCalOptions').fadeIn('fast');
      }
    );

Upvotes: 1

vher2
vher2

Reputation: 990

Try this:

$(function(){
    $(document).on("click", ".addtocal", function(){
        $(this).next('.addToCalOptions').fadeIn('fast');
    }
);

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

You could use document as delegate, because delegate have to be static (not dynamically added):

$(function(){
  $(document).on("click", ".addtocal", function(){
  $(this).next('.addToCalOptions').fadeIn('fast');
  }
);

But better is to use closest static container instead of document.

Upvotes: 4

Related Questions