Magento 2

How to add modal popup in Magento 2.4

Magento 2

How to add modal popup in Magento 2.4

When working with Magento 2, we try to take advantage of all the utilities that Magento has supported, to avoid having to rework the existing features, which causes time and effort.

In this post, I am going to explain how to create and call modal popup widget in Magento 2.

Let’s create note.phtml file in vendor/vendor-name/module-name/view/frontend/templates/

<div id="popup-modal" style="display:none;">
    <h3> This is content </h3>
</div>

<button id="modal-btn">Open Modal</button>


<script>
    require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {
           $("#modal-btn").on('click', function() {
                 var options = {
                     type: 'popup',
                     responsive: true,
                     innerScroll: true,
                     title: 'Popup Title',
                     buttons: [{
                         text: $.mage.__('Close'),
                         class: '',
                         click: function() {
                             this.closeModal();
                         },
                     }, {
                         text: $.mage.__('Buy Now'),
                         class: '',
                         click: function() {
                             alert("Add your code");
                         },
                     }]
                 };

                var popup = modal(options, $('#popup-modal'));

                $('#popup-modal').modal('openModal');
            });
        });
</script>

Hopefully, this post is useful to you.

Happy Coding!