Coveo for Sitecore 5 is now available!

Binding Custom Event Handlers Using the Coveo for Sitecore Legacy Search UI Framework jQuery Plug-In

Coveo for Sitecore 4.1 (November 2018)

When developing a search-driven website, you will often want to execute custom logic before or after the search query is performed. This article shows how this can be achieved.

  1. Create a new Sitecore page using the Coveo-Powered Search Page template. The page should look like this:

  2. If you wanted to add custom logic, the first thing you would need to do is modify the query before it’s performed. The second thing to do is to output statistics in the browser console. To do so, edit the CoveoSearch.ascx file which is located in the layouts/Coveo folder of your Sitecore instance. Then, insert the code below:

     Coveo.$(function() {
         var options = <%= Model.GetJavaScriptInitializationOptions() %>;
         // ADDED CODE -->
             .on('buildingQuery', function (e, args) {
             .on('querySuccess', function (e, args) {
                 console.log('Query returned ' + args.results.totalCount + ' results in ' + args.results.duration + 'ms.');
         // <-- ADDED CODE
         Coveo.$('#search').coveoForSitecore('init', options);

    Using the on jQuery method, you attached two event handlers to the buildingQuery and querySuccess events (see the list of JavaScript Search Framework Events). Since the buildingQuery event is fired before the query is performed, it’s the preferred event to alter the query expression. In this case, you can added the search term to the query. The querySuccess event, on the other hand, is fired when the query succeeds. In this case, you can output the total number of results and the query duration in the browser console.

  3. When reloading the page, you can see how it changes.

    As you can see, by default, the search query uses the search term. Notice that there are now 234 results instead of 2847. Also, if you look at the browser console, you can see the custom trace.

     Query returned 234 results in 30ms.
What's Next for Me?