Magento – Add javascript in custom widget

customjavascriptmagento2widget

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.

Best Answer

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" />