CJe
CJe

Reputation: 1992

How to handle nested events in jQuery

I have a

<span class="fold"></span>

that's handled by a

$('.fold').click(function (event) { ... });

Now the click event adds new "fold" classes through ajax that I would like to assign the same event handler to. Is that possible and if so where in the logic would I "re"-add my click handler?

Thanks in advance

Upvotes: 2

Views: 1650

Answers (2)

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

Just write:

$(".fold").on("click", function(event){
  //write code
});

Update: For dynamically appended elements write this:

$(document).on('click', '.fold', function(e) {
    // write code
});

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337580

If you are dynamically adding elements which require handlers, use a delegated event handler like this:

$(document).on('click', '.fold', function(e) {
    // do stuff
});

Note that for best performance you should replace document with the selector of the element which the .fold elements are being appended to.

Upvotes: 5

Related Questions