When you add the eva
function via addEventListener
, it's an undefined variable. Then, you set it to a function. Essentially, when you write it like you have:
var myForm = document.forms["form1"];
myForm.addEventListener("submit", eva);
var eva = function() {
alert("hello");
}
You're effectively writing this:
var myForm = document.forms["form1"];
var eva; // = undefined
myForm.addEventListener("submit", eva);
eva = function() {
alert("hello");
}
The declaration of the var
gets hoisted, but not the assignment. By using a function declaration, function eva() { ... }
gets similarly hoisted to the top of the scope and is a valid function when you pass it to addEventListener
.
So, you have two options:
- Move the var declaration and assignment above the call to
addEventListener
.
- Use the function declaration.