2

I've created a custom widget with a popup on homepage loading, now i need a function to close the popup but i'm not able to include a javascript file in the widget. I've tried the solution that i read in other post but i haven't find the solution yet.

Magento version: 2.1.7

Hope someone can help me, thank you in advance.

  • when you say a 'custom widget' do you mean that you created a widget type other then the default ones that you select in the dropdown when you make a new widget? In most cases the widget is pulling in a static block that you can include your js in, are you doing something else here? – circlesix Aug 9 '17 at 1:37
  • I've created another widget type, i'm using it only for the popup – Roberto Barile Aug 9 '17 at 9:39
  • could you include the code you used to create it? – circlesix Aug 9 '17 at 13:36
5

Create requirejs-config

var config = {
    map: {
        '*': {
            yourWidgetName: 'NameSpace_ModuleName/js/yourwidgetfile',  
        }
    },
};

Define you widget following convention

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

    $.widget('namespace.yourWidgetName', {
      // Logicial code

      // Optional 
      options: {
         // Define variables
      },

      _create: function() {
         // Init code
         this.closeModal();
      },

      closeModal: function() {
         // Do close modal here
      },


    });

    return $.namespace.yourWidgetName;
});

For use widget you can call it anywhere if it defined. Such as in template

<div data-mage-init='{"yourWidgetName": {}}' class="container-wrapper" />
0

I've resolved the problem using the following script:

<script>
require(
    [
        'jquery',
        'Magento_Ui/js/modal/modal'
    ],
    function(
        $,
        modal
    ) {
        var options = {
            type: 'popup',
            responsive: true,
            innerScroll: true,
            title: 'Iscriviti al nostro sito',
            buttons: [{
                text: $.mage.__('Continue'),
                class: '',
                click: function () {
                    this.closeModal();
                }
            }]
        };

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

        $('#popup-modal').modal('openModal');
    }
);

Anyway thank you for the help, i hope this can be useful for other users

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.