Using JavaScript In The Recommendation Templates

As with CSS, you can add JavaScript to the recommendations by adding an inline script block to the template. The script is evaluated and executed when the recommendations are loaded, but unlike the style block and the HTML content, the JavaScript block will not be visible in the source after page load.

Targeting the right window object

Since the Nosto JS is loaded in an iframe, the scripts are executed in another window context. This is useful since it prevents the script from clashing with other scripts on the site. The downside is that manipulating the DOM and initializing scripts from the template gets a little trickier, since the scripts are not loaded in the same window as the site. To use the scripts you are loading on the site, you need to choose the right window object: _targetWindow. For example if you are loading jQuery on your site, instead of calling $ or jQuery you would use it by calling _targetWindow.$ or _targetWindow.jQuery.

Selecting elements with jQuery

If you are implementing functionality with JavaScript, you usually want to be able to target certain elements inside the recommendation template. A jQuery selector targeting an element in the template works fine as long as there is only one recommendation loaded on the page:

However if the same template is included on the page more than once, the selector would match multiple elements and it would be likely to cause problems. As when enclosing CSS styles in the template, you can use the $divId variable to create a selector that only matches elements inside the current recommendation slot:

This way the selector will be unique each time the template is included into the page and there won’t be any issues with the selector matching more than the intended elements.

Was this article useful?

← Previous
Useful Design Patterns
Next →
Styling The Recommendations