Pixelknight1398 Pixelknight1398 - 1 year ago 98
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();};


d.onclick = "myFunction()";


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 =)

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

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

Answer Source
elem.addEventListener("click", function, false); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download