Calling and initializing JavaScript in Magento2

In this topic we describes different ways to call and initialize JavaScript in Magento 2. Subscribe to Bethos for all the Magento2 problems and customizations.

Types of Calling and Initializing Javascript:

  • Declarative notation
  • Imperative notation

In this post we explain Declarative Notation with examples.

Two options for specifying declarative notation:

  • Using the data-mage-init attribute
  • Using <script type="text/x-magento-init"> ... </script> tag
Using the data-mage-init attribute:

This is used to target a specific HTML element. This method can only be implemented on the specified HTML tag.

For example: In your phtml you can use the code like below.

In the above example, We passed Bnethos_JSmodal/js/examplemodal custom js in data-mage-init attribute. Now you can write your custom functions in the passed javascript. Add your javascript, under app/code/Bnethos/JSmodal/view/frontend/web/js/examplemodal.js . For example:

Using <script type="text/x-magento-init"> ... </script> tag:

This is used to target either a CSS selector or *. If the CSS selector matches multiple HTML elements, the script will run for each matched HTML element. For *, no HTML element is selected and the script will run once with the HTML DOM as its target. This is preferred when direct access to the HTML element is restricted, or when there is no target HTML element.

Example code for * below:

Example code for CSS selector:

In the above examples you can see CSS selector and * are used to map the elements. We passed Bnethos_JSmodal/js/examplemodal js. It is the same custom Javascript we used in the above Custom (ExampleModal.js)Javascript Section.

If you need more help regarding this post, feel free to ask in the Comments section below.I would be happy to solve your queries.

Related Topic: Pass data from phtml to javascript using Declarative notation

1 thought on “Calling and initializing JavaScript in Magento2”

Leave a Comment