How to create a popup in Magento 2

Magento 2 makes many things to support the developers in custom their webshop in an easy way. Popup is good to go strategy to attract visitors’ attention and engage them thoroughly to explore the website with more curiosity. So this article helps us learn the way to create a simple popup with a Modal widget in Magento.

With the modal widget, the developers can make a popup quickly. Now, we’ll learn how to create a popup in Magento by Modal widget.

Step 1: Create a template file.

<?php
/**
 * Fill content of popup in 'simple-modal_popup' element.
 */
?>
<div id="simple-modal_popup" style="display: none">
    <div>I love Magento 2.</div>
</div>
<div id="open-modal_popup" style="margin: 10px">
    <button class="action"><?= __('Click me to open popup!');?></button>
</div>
<script type="text/x-magento-init">
    {
       "#open-modal_popup": {
           "AlbertTran_Popup/js/popup": {}
       }
    }
</script>

Step 2: Make js file to open popup.

define(
    [
        'jquery',
        'Magento_Ui/js/modal/modal'
    ],
    function($) {
        "use strict";

        $.widget('AlbertTran.ModalPopup', {
            options: {
                modalForm: '#simple-modal_popup',
                modalButton: '#open-modal_popup'
            },
            _create: function() {
                this.options.modalOption = this.getModalOptions();
                this._bind();
            },

            getModalOptions: function() {
                return {
                    type: 'popup',
                    responsive: true,
                    clickableOverlay: false,
                    title: $.mage.__('Modal PopUp'),
                    modalClass: 'popup',
                    buttons: [{
                        text: $.mage.__('Click me to close!'),
                        class: '',
                        click: function () {
                            this.closeModal();
                        }
                    }]
                };
            },

            _bind: function(){
                var modalOption = this.options.modalOption;
                var modalForm = this.options.modalForm;

                $(document).on('click', this.options.modalButton, function(){
                    $(modalForm).modal(modalOption);
                    $(modalForm).trigger('openModal');
                });
            }
        });

        return $.AlbertTran.ModalPopup;
    }
);

Step 3: Clear cache and check your result.

We made a modal popup successfully.

Source code: https://github.com/Albert-Tran/magento2-popup

Blog Comments

Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
Commenter avatars come from Gravatar.

Leave a Comment