1

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.

  • Do you want this by module? – Sohel Rana Apr 1 '17 at 15:07
  • @SohelRana What will be best option? I want to create separate files for custom jquery functions. So please suggest how I can register this file in all pages and call its function from any where. Or on some specific pages also. – Bal Singh Apr 2 '17 at 3:55
4

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>
  • I tried this but it not working. Its throwing the error in console: Uncaught TypeError: Cannot read property 'showDivtest' of undefined – Bal Singh Apr 2 '17 at 4:05
  • @BalSingh see my updated answer. Remember to delete and run static content deploy again. – Khoa TruongDinh Apr 2 '17 at 5:11
  • Yes its working. Can be call this function in html onclick event? like <a href="javascript:void(0)" onclick="script.showDivtest();"> – Bal Singh Apr 2 '17 at 6:09
  • You should create a jQuery Widget. Or, in your custom function customfunctions.js, you should return a function which includes the code for click event. – Khoa TruongDinh Apr 2 '17 at 7:49

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.