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

How to use custom jQuery code?

jQuery code can be placed in your (child) theme's main JavaScript file. Alternatively, you can add it manually between <script> tags in the <head> section of your (child) theme's header.php file. You can also load it with a hook in your (child) theme's functions.php file, or in the Custom Hooks add-on. To load the code only on pages with facets, use the facetwp_scripts hook. To load it on all pages, use wp_head or wp_footer. Or you can use a code snippets plugin. Note that jQuery code needs the jQuery library loaded. If it is not already loaded, you can enable jQuery in FacetWP's settings. More info

$('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

How to use custom jQuery code?

jQuery code can be placed in your (child) theme's main JavaScript file. Alternatively, you can add it manually between <script> tags in the <head> section of your (child) theme's header.php file. You can also load it with a hook in your (child) theme's functions.php file, or in the Custom Hooks add-on. To load the code only on pages with facets, use the facetwp_scripts hook. To load it on all pages, use wp_head or wp_footer. Or you can use a code snippets plugin. Note that jQuery code needs the jQuery library loaded. If it is not already loaded, you can enable jQuery in FacetWP's settings. More info

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

Last updated: September 10, 2024