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– Sohel Rana2017年04月01日 15:07:17 +00:00Commented 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.Bal Singh– Bal Singh2017年04月02日 03:55:26 +00:00Commented Apr 2, 2017 at 3:55
1 Answer 1
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 undefinedBal Singh– Bal Singh2017年04月02日 04:05:11 +00:00Commented Apr 2, 2017 at 4:05 -
@BalSingh see my updated answer. Remember to delete and run static content deploy again.Khoa Truong– Khoa Truong2017年04月02日 05:11:22 +00:00Commented 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();">Bal Singh– Bal Singh2017年04月02日 06:09:26 +00:00Commented 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.Khoa Truong– Khoa Truong2017年04月02日 07:49:38 +00:00Commented Apr 2, 2017 at 7:49
Explore related questions
See similar questions with these tags.