PART 1.2.5 – jQuery widgets and require.js

Useful resources:

Initializing js


Example from layered navigation in Luma (theme-frontend-luma/Magento_LayeredNavigation/templates/layer/state.phtml)

When inserted in a certain element, the script is called only for this particular element. It is not automatically called for other elements of this type on the page.

<script type=”text/x-magento-init”>

Example from add to cart module-catalog/view/frontend/templates/product/view/addtocart.phtml  

To call a JS component on a HTML element without direct access to the element or with no relation to a certain element, use the <script type=”text/x-magento-init”> tag and attribute.


Some of the common ones include:

  • Accordion
  • Collapsible
  • Dropdown
  • Modal

Gallery widget


Example of how to add a new javascript

In the root of your theme add: a file named requirejs-config.js 





 * Copyright © 2009-2017 Vaimo Group. All rights reserved.

 * See LICENSE.txt for license details.



var config = {

    “map”: {

        “*”: {

            example: “js/example”




Create the js file




 * Copyright © 2009-2017 Vaimo Group. All rights reserved.

 * See LICENSE.txt for license details.




], function($) {

    $.widget(“vaimo.example”, {

        options: {

            color: ‘#fafafa’



        _create: function () {

            console.log(‘This is the background color: ‘ + this.options.color);




Initialization using data-mage-init


<footer data-mage-init=‘{“example”:{“color”: “#fab”}}’ class=“footer content”>


class=“footer__cms accordion accordion-container”>


class=“accordion-title footer__title”>



                echo __(‘Customer service’) ?>




class=“accordion-content footer__cms-links”>

            echo $block->getChildHtml(‘footer.links’) ?>






Exercise 8.0

  1. Create a js file in your theme.
  2. Include the js file using require-js.
  3. Intiate the js using data-mage-init on the div with the class products inside list.phtml (the template used in exercise 6)
  4. The script should add a class, color or console log a string when the product list is rendered.

Leave a Reply

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

You are commenting using your 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