JavaScript function is not defined with Laravel Mix JavaScript function is not defined with Laravel Mix laravel laravel

JavaScript function is not defined with Laravel Mix


I had the same problem as you.

It turned out that when Laravel-mix, aka Webpack, compile the js, it wraps our function in a closure.

For example, when we define a function like this

function setlocale(code) {     console.log(code);}

Webpack will generate into

(function(module, exports, __webpack_require__) {     function setlocale(code) {         console.log(code);     }});

That's why we can access the variables or functions inside that closure, but we cannot from the outside as it limits our scope.

A simple solution is setting our function into window variable, which is a global variable.

window.setlocale = function (code) {    console.log(code);}


As window object is not accessible when building/packaging assets through laravel mix / webpack, so thats why onclick event handler becomes undefined for the code itself. So if the window.setlocale approach doesn't fit well with you then an alternative would be to bind using the jQuery click event e.g.

$("#button-id").on("click",function() => {       // enter code here})


update the code in resources/js/app.js as below-

button1Clicked = function(){    console.log('Button 1 is clicked');};

then it will be available for global scope.