Tarta Tarta - 1 month ago 6
HTML Question

Calling a function in a .js file from a .html file

I found many answers about this topic but it seems that they all do something I don't want. It should be a relatively easy question though.

In my html I have:

<button onclick= "myFunction();">Ptin Text</button>


while in my .js file I have:

function myFunction() {
console.log("foo");
}


the .js file is included correctly at the end of my html but still the error I get is that the function myFunction() is not found. How can I achieve this? Thank you in advance

EDIT: The function is defined inside a scope:

$(document).ready(function () {
function myFunction() {
console.log("foo");
}
}


I understand that my html is not able to see within that scope, but why? Since the function is defined if the DOM is ready, it should be indeed able to see it.

Answer

Events that are defined inline using an attribute (onclick= "myFunction();") can only access functions that are defined in the global scope.

A better idea would be to use addEventListener or jQuery.on to add event listeners.

$(document).ready(function () {
   function myFunction() {
    console.log("foo");
   }

   $('button').on('click', myFunction);
}

If you have multiple button elements then you need to use an id or class.