Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between $('.class').on and $(document).on in jquery

What are the differences between

$(document).on('click', '.class', function() {
   //stuff
});

And

$(".class").on("click", function () {
    //stuff
});
like image 316
Twinsen Avatar asked Sep 03 '25 10:09

Twinsen


1 Answers

The first subscribes to the .click event in a lively manner. This means that it will listen for DOM changes and if in the future someone add an element with class="class" it will have the click handler attaced.

The second will subscribe to the click handler of all elements with class="class" at the moment you are making this subscription. If for example in the future you make an AJAX request and inject into your DOM an element with this class, it won't have the click event applied to it.

like image 197
Darin Dimitrov Avatar answered Sep 04 '25 23:09

Darin Dimitrov