Using jQuery with Algolia / WooCommerce

Hi @rayrutjes,

Quick question. I wanted to get the text of the facet link (hierarchical menu) clicked on with jQuery. Because of the nature of the hierarchical menu and plugins, you can’t propagate .on(click) to dynamic menu items that haven’t appeared yet.

Do you have any suggestions or a best practice for how to listen for a change in the facet menu?

Thanks :slight_smile:

1 Like

Hi @trplustr,

In general, when you want to listen for events on multiple similar items and apply the same callback, it is a best practise to “delegate” the listening to a parent container higher in the hierarchy.

Here is a more in detail explanation: https://learn.jquery.com/events/event-delegation/

I hope that helps :wink:

1 Like

Thanks @rayrutjes , That’s exactly what I’ve been trying. Using a delegate like $( document).on( “click”, “a”, function… and it works everywhere else, including the dynamic InstantSearch hits, but not the facet links. I figure it has been disabled somewhere intentionally.

Is it just me? I keep trying different things. If you think of anything else let me know, and thanks again!

Hi,

What is your underlying use case for having to know which hierarchical facet item was clicked? Understanding this will help us provide you solutions.

Also if you can, publish a small jsFiddle here: http://jsfiddle.net/. This will help us work on code together. Thanks

Hello vvo,

I’ve created a JSFiddle here: https://jsfiddle.net/fqzcby0n/ It’s not a full recreation of the instantsearch environment but you can see the basic script that doesn’t seem to work (It does work in the fiddle).

The purpose is to get the category name clicked on and send it through AJAX in WordPress to get additional custom category info. The client has requested the ability to have dynamic content outside of the Algolia wrapper that relates to the search. Everything else works fine. The facet links just don’t bubble up or propagate.

My alternate approach is reading something like a currentRefinedValues filter (a bit slower). I can put that somewhere easily, but without being able to listen for clicks, I’d have to use some other kind of observer.

Hope that makes sense. Just looking for something like in the Fiddle that works with facet links.

Thanks for your time :slight_smile:

@trplustr That should solve it: https://jsfiddle.net/0o3p6sps/3/

This solution requires a bit of helper state knowledge but is the safest one, not relying on DOM parsing.

Let me know how it goes.

Ultimately it’s feasible to register click on the document for all widgets in instantsearch.js but you have to do it in vanilla JS (document.addEventListener), somehow jQuery is not working for this here.

2 Likes

Thanks @vvo,

I appreciate the code and ideas. It has been useful. :+1: