Magento 2.1 jQuery – How to Call Custom jQuery Function in PHTML

jquerymagento-2.1magento2requirejs

I have some custom jquery functions and I want to create a common js files for all custom functions. But I am unable to find a way to achieve this.

I have created requirejs-config.js file at theme root(app/desgin/frontend/Vendor/Theme/). Content of requirejs-config.js file is:

var config = {
map: {
   '*': {
       'customfunctions' : 'js/customfunctions',
   }
},
paths: {
},};

Then I have created a customfunctions.js file which has custom functions. Path of file is app/desgin/frontend/Vendor/Theme/web/js. Content of customfunctions.js file is:

define(['jquery'], 
   function($) {
      function showDivtest() {
         alert("I am here");
      }
   };

Now, how I can call showDivtest() function in phtml file? Please suggest.

Best Answer

Your custom script should change:

define(['jquery'],
 function($) {
    'use strict';
    return  {
        showDivtest: function () {
          alert("I am here");
        }
    }

});

Call via require Js in the template. For example, in your template:

<script> 
    require([
        'customfunctions'
    ], function (script) {
        script.showDivtest()
    });  
</script>
Related Topic