...

View Full Version : onClick event fires when the page loads...



iLochie
09-06-2010, 10:50 AM
Alright, so I'm working on a script, and I'm simply using the following code:

document.getElementById("element").onclick = alert("hello");

When I load the page, the alert fires instantaneously. I'm completely stumped. I've checked everything in my not too extensive Javascript file, and it looks fine. What common errors could cause this?

Philip M
09-06-2010, 11:30 AM
That is not valid Javascript syntax. Consult your error console.

What you want is


<span id = "element" onclick = "alert('Hello')">Philip M</span>


Quizmaster: The cape on which the Pilgrim Fathers landed in 1620 is named after which fish?
Contestant: Haddock

Dormilich
09-06-2010, 01:01 PM
all the event handlers expect a function to be given, not the result of a function call*. i.e.

document.getElementById("element").onclick = function (evt) { alert("hello"); }

* - unless that result is a function itself.

iLochie
09-06-2010, 08:35 PM
all the event handlers expect a function to be given, not the result of a function call*. i.e.

document.getElementById("element").onclick = function (evt) { alert("hello"); }

* - unless that result is a function itself.
Thank you, I'll give that a try. And Philip, I was hoping to avoid that. ;)

Philip M
09-06-2010, 09:48 PM
And Philip, I was hoping to avoid that. ;)

Why? Why go for complication? I agree that dormilich's script is "unobtrusive" but why does it matter?

Dormilich
09-06-2010, 11:52 PM
I agree that dormilich's script is "unobtrusive" but why does it matter?

maintenance, readability & code re-use



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum