Handling a facet option selection event in Coveo

While I was able to find some other notable results on this topic, none of them quite helped me achieve this completely, so I thought I’d provide my own solution for this. In Coveo if you ever need to handle a click or select event on one of your facets, you can do so using code similar to the following:

    Coveo.$('.CoveoSearchInterface').on('state:change:f:@aopasitename', function (e, data)  {
        console.log('Facet State has changed, the new value is: ' + data.value);
    });

Prior to writing this blog post, I found a very similar solution here. Except I was confused by the $('#search') part, as I didn’t have any element with that id, and I couldn’t figure out what element this was supposed to be pointing to (until I Google-searched that specific selector and found a page explaining what it was). Let’s break this code down:

  1. Coveo.$('.CoveoSearchInterface') is a selector to my current search interface. This is a div which encompasses the entire search interface (makes sense) – so, including the search box, facets, results section and other sections.  Your search interface might be a div with id “search”. For me, it is a div containing a class, “CoveoSearchInterface” . I believe the naming of this class is specific to Coveo Hive.
  2. Calling .on() latches onto the search interface div. The first parameter is the name of the event. So because we want to handle when a facet option is selected, we really want to hook into the state change event (because Coveo state changes when a facet is selected or deselected). For more information on state check out this detailed document.
  3. Finally, you need to provide the name of a field. This field would be hooked up to the facet you are trying to handle changes for (Hint: You can get this from the URL query string after selecting an option in your facet.) If it is a custom/external (non-Sitecore) field, then you can use @ followed by the field name. Otherwise, you will need to convert the field name to a Coveo for Sitecore field name using one of the following helper functions:
    1. If using Coveo Hive, use coveoFieldName("myFieldName").
    2. Otherwise, use ToCoveoFieldName("myFieldName").

Lastly, the f: is included because we are referencing a state attribute name. So your actual state attribute name would be f:[yourFieldName].

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s