views:

180

answers:

3

The following function is supposed to execute during the "onload" event of my webpage.

function setUpTranslation() {
   var phrases = document.getElementsByTagName("p");

   for (i = 0; i<phrases.length; i++) {
      phrases[i].number = i;
      phrases[i].childNodes[1].innerHTML = french[i];

      phrases[i].childNodes[1].onMouseDown = alert("Hello World");
  }
}

Can anyone tell me why the alert happens each time through the For loop? I'm expecting that it would only happen when the user presses the mouse on one of the phrases in my list.

Someone said that onmousedown shouldn't be capitalized but when I do that I get an error saying "not implemented"

Thank you in advance for your help.

+2  A: 

That's because you're calling it. What you want is to create a function that calls alert when it's called:

  phrases[i].childNodes[1].onMouseDown = function() {alert("Hello World");};
Max Shawabkeh
beat me by 25 seconds, damn
Dan Beam
+1  A: 
phrases[i].childNodes[1].onMouseDown = alert("Hello World");

should be

phrases[i].childNodes[1].onMouseDown = function( ){ alert("Hello World"); };

otherwise it's return the value of alert as the handler (which is undefined and does nothing).

Dan Beam
+1  A: 

You're setting the onMouseDown event to the result of alert("Hello World"), not a function. Change it to something like this to keep it from running until you intend it to run:

phrases[i].childNodes[1].onMouseDown = function() { alert("Hello World"); };

This makes a function with the alert as the body of the function, and sets that function as the callback of the onMouseDown event.

Aaron