Hello World

We will introduce some of the core concepts of the Klevu JavaScript Library by stepping through a very basic implementation to add a search box to a static page which will produce auto-suggest terms from the Klevu API as you type.

tl;dr

Scroll down to the JS Fiddle at the bottom of this page which includes the JS, HTML and a working example. The code snippets in this article omit some of the code in order to focus on the most important aspects, so refer to the JS Fiddle for the full example.

HTML

We start with a basic HTML page with a search box and the Klevu JavaScript Library core JS file included. We are using the debug version here, hosted by Klevu, but you can optionally download this yourself and we recommend using the minified version for your Production store.

<!DOCTYPE html>
<html>
<body>
    <form>
        <input type="text" name="q" id="search" />
    </form>

    <script src="//js.klevu.com/klevu-js-v2/2.0/klevu_debug.js"></script>
</body>
</html>

Everything else is your own code that you can choose how to write, as the only JavaScript Klevu maintains is the above core library JS file.

Micro-Templates

The next HTML to add is a template, or micro-template, which will render our auto-suggestions in a list when we start typing in the search box. The ID KlevuTemplateAutoSuggestion can be whatever you like, but it is important as it is referenced in the JS later on.

<script type="template/klevu" id="KlevuTemplateAutoSuggestion">
    <% if(data.suggestions.autosuggestion) { %>
        <% if(data.suggestions.autosuggestion.length> 0 ) { %>
            <ul>
                <% helper.each(data.suggestions.autosuggestion, function(key, suggestion) { %>
                    <li><%=suggestion.suggest %></li>
                <% }); %>
            </ul>
        <% } %>
    <% } %>
</script>

Settings

Next we’ll add some settings. The use of klevu.interactive is to prevent activation of the search functionality until all relevant resources have been loaded.

klevu.interactive(function() {
    klevuInit();
});
function klevuInit() {
    var options = {
        search: {
            minChars: 1,
            searchBoxSelector: "#search",
            apiKey: "klevu-14728819608184175"
        }
    };
    klevu(options);
}

Events

The Klevu JavaScript Library is event driven and in order to initialise our search boxes we define some new events, including one called MySecondEvent.

This event will execute from the time of creation for maxCount times with an interval of delay or until the event evaluates to true via the fire function. This allows us to check that everything is ready before triggering the rest of our functionality, via event listeners or observers.

klevu.coreEvent.build({
    name: "MySecondEvent",
    fire: function () {
        if (
            klevu.isUndefined(klevu.search.extraSearchBox)
            || (klevu.search.extraSearchBox.length == 0)
        ) {
            return false;
        } else {
            return true;
        }
    },
    maxCount: 500,
    delay: 30
});

When the conditions of this event have been satisfied any listeners attached to this event will fire. The following event listener will associate the HTML template we created above with the search box, with a name of klevuAutoSuggestTarget.

klevu.coreEvent.attach("MySecondEvent", {
    fire: function () {
        klevu.each(klevu.search.extraSearchBox, function (key, box) {
            box.getScope().template.setTemplate(klevu.dom.helpers.getHTML("#KlevuTemplateAutoSuggestion"), "klevuAutoSuggestTarget", true);
        });
    }
});

Chains

Another event listener will perform the more interesting parts, which is where we introduce the concept of Chains in Klevu JavaScript Library to:

  • specify some data to retrieve during the Klevu API request.
  • specify what to do with that data when the response comes back.

The below is an addition to the API request building chain, in order to add a new request for some autosuggestions, 5 to be precise, and include them in the response when you start typing something in the search box.

box.getScope().chains.request.build.add({
    fire: function (data, scope) {
        var parameterMap = klevu.getSetting(scope.kScope.settings, "settings.search.map", false);
        var suggestion = klevu.extend(true, {}, parameterMap.suggestions);

        suggestion.id = "autosuggestion";
        suggestion.query = data.context.term;
        suggestion.typeOfRequest = "AUTO_SUGGESTIONS";
        suggestion.limit = 5;

        data.request.current.suggestions.push(suggestion);
        data.context.doSearch = true;
    }
});

The next adds to the template rendering chain, in order to populate the page with our klevuAutoSuggestTarget template when the result contains autosuggestion data.

box.getScope().chains.template.render.add({
    fire: function (data, scope) {
        if (data.context.isSuccess) {
            scope.kScope.template.setData(data.template);
            var targetBox = "klevuAutoSuggestTarget";
            var element = scope.kScope.template.convertTemplate(scope.kScope.template.render(targetBox));
            var target = klevu.getSetting(scope.kScope.settings, "settings.search.searchBoxTarget");
            target.innerHTML = '';
            
            scope.kScope.element.kData = data.template;
            scope.kScope.template.insertTemplate(target, element);
        }
    }
});

The Result

Putting all of the above concepts together, we have a simple HTML search box which will produce auto-suggestion terms, products, categories and CMS via the Klevu API when typing. We recommend doing this with the network tab open so you can see the API requests and responses.

Click on the ‘Result’ tab below to try it.

Give it a try for yourself then head over to our GitHub repository to try some more advanced examples of what you can achieve with Klevu JavaScript Library.