tags:

views:

310

answers:

3

i am creating an empty div in the javacript DOM. but when i call some function on it, for example,

 var hover = document.createElement("div");
 hover.className = "hover";
 overlay.appendChild(hover);
 hover.onClick = alert("hi");

the onClick function isnt working. instead it displays an alert as soon as it reaches the div creation part of the script. what am i doing wrong?

+2  A: 

You need to put the onclick in a function, something like this:

hover.onclick = function() {
   alert('hi!');
}
ylebre
this has solved the problem somewhat. but now the alert doesnt even gets displayed even upon clicking on the hover area.to be more informative, the hover is an empty div. and the css class definition:.hover { width: 320px; height: 75px; position: absolute; left: 28%; top:32%; z-index: 9999; background-color: #000; overflow: hidden;}
amit
+3  A: 

Try addEventHandler & attachEvent to attach event to an element :

if (hover.addEventListener)
{
 // addEventHandler Sample :
 hover.addEventListener('click',function () {
  alert("hi");
 },false);
}
else if (hover.attachEvent)
{
 // attachEvent sample : 
 hover.attachEvent('onclick',function () {
  alert("hi");
 });
}
else
{
 hover.onclick = function () { alert("hi"); };
}
Canavar
awesome. this worked.
amit
This will only work in browsers that comply with the W3C event model. For IE you'll have to use attachEvent..
J-P
Thanks J-P, I updated my answer.
Canavar
A: 

The property name is "onclick" not "onClick". JavaScript is case sensitive.

It also takes a function. The return value of alert(someString) is not a function.

David Dorward