X Features Cars Demo Power Plants Demo State Parks Demo Site Showcase Docs Tutorials Add-ons Buy

Use jQuery .on() instead of .click()

Let’s say you’re using jQuery to listen for clicks of .tooltip link elements. You’ve probably seen code like this before:

$('a.tooltip').click(function() { /* do something */ });

There’s a couple improvements that can be made to the above code.

Use .on() instead of .click()

jQuery’s .on() supports dynamically-added elements, such as those created during AJAX requests (hint hint, FacetWP). It listens to changes in the DOM, unlike with .click().

Target parents instead

If you target the a.tooltip selector directly and there’s 100 tooltips on your page, then jQuery has to create bindings for all 100 elements. It’s often better to find a parent item (one that won’t change), or using document itself.

End result

$(document).on('click', 'a.tooltip', function() { /* do something */ });