Empty div not recognized in javascript

I am creating an empty div in javascript DOM. but when I call on it some function, for example,

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

the onClick function does not work. Instead, it displays a warning as soon as it reaches the div script creation part. What am I doing wrong?

+4
source share
3 answers

Try addEventHandler and attachEvent to attach an 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"); }; } 
+4
source

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

 hover.onclick = function() { alert('hi!'); } 
+2
source

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

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

0
source

Source: https://habr.com/ru/post/1286171/


All Articles