Magento 2.x – How to create a frontend modal popup from scratch

A Modal Window helps with this by making the whole page darker and highlighting the modal window in the center.

You can perform the following steps to create it on the Magento way.

  • Create a default.xml  file inside the layout folder of your module and add the following code to it:
  • Create the template modal_example.phtml file in templates folder and insert the following code to it:
  • Next step is to add a JS file to initialize and execute the component, to do so, we will need example-modal.js file in app/code/Offset101/ModalPopup/view/frontend/web/js/ directory:

    The example-modal.js  file should be declared in the requirejs-config.js  file because this config file is used by RequireJS.
  • So, create the requirejs-config.js file in app/code/Offset101/ModalPopup/view/frontend/ directory and add the following code to it:
  • Last step, is to create our example Block to provide all bussiness logic, so let’s create the Example.php file in app/code/Offset101/ModalPopup/Block/ directory, with the following content:

    And that’s it, we are able to test our new modal popup, but before that, remember to run:

    Happy Coding!