Pixelknight1398 Pixelknight1398 - 2 months ago 6
HTML Question

Setting onclick function dynamically in Javascript not working

hello =) I am trying to create a heading tag with some text in it.

var d = document.createElement("h5");
d.innerHTML = "Dungeon";


and then assigning an onclick listener.

d.onclick = function(){myFunction()};


which doesn't seem to be working. I've also tried

d.onmousedown = function(){myFunction();};


and

d.onclick = "myFunction()";


and

d.addEventListener("mousedown", function(){myFunction});


and none of them seem to be working. I have thrown in a couple tracers around it, everything runs through fine without syntax errors but the actual element when appended to the document doesn't have the function tied to it at all. Would anyone happen to know why? Thanks in advance =)

Edit:
Here is a more detailed block of my code. Would this make any difference?

var x = document.createElement("ul");
var y = document.createElement("li");
x.appendChild(y);
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
y.appendChild(d);
console.log(0);
d.onclick = function() { alert('test'); }
console.log(1);

Answer
elem.addEventListener("click", function, false); 
Comments