0

I do not know why the code below does not work! But if i change var eva = function(){alert("hello");} to function eva() {alert("hello");}, it works.

var myForm = document.forms["form1"];

myForm.addEventListener("submit", eva);

var eva = function() {
alert("hello");
}
Will
  • 503
  • 8
  • 22
  • Why should that code work? You're using a variable you haven't defined yet. – Ian Dec 06 '13 at 14:15
  • Look up 'differences in variable hoisting between function expressions and function declarations.' – Andy Dec 06 '13 at 14:15
  • Reference: http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1 – Ian Dec 06 '13 at 14:16

2 Answers2

2

eva is not defined at the point where you use it.

However, this does work:

var myForm = document.forms["form1"];

var eva = function() {
alert("hello");
}

myForm.addEventListener("submit", eva);
Kendall Frey
  • 39,334
  • 18
  • 104
  • 142
2

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:

  1. Move the var declaration and assignment above the call to addEventListener.
  2. Use the function declaration.
FishBasketGordo
  • 21,938
  • 4
  • 54
  • 88