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.

Khoa Truong
32.5k11 gold badges91 silver badges159 bronze badges
asked Apr 1, 2017 at 11:12
2
  • Do you want this by module? Commented Apr 1, 2017 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. Commented Apr 2, 2017 at 3:55

1 Answer 1

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>
answered Apr 1, 2017 at 15:21
4
  • I tried this but it not working. Its throwing the error in console: Uncaught TypeError: Cannot read property 'showDivtest' of undefined Commented Apr 2, 2017 at 4:05
  • @BalSingh see my updated answer. Remember to delete and run static content deploy again. Commented Apr 2, 2017 at 5:11
  • Yes its working. Can be call this function in html onclick event? like <a href="javascript:void(0)" onclick="script.showDivtest();"> Commented Apr 2, 2017 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. Commented Apr 2, 2017 at 7:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.