I have a following code:
document.body.onload = addElement;
function addElement () { var myImage = new Image(400, 100);
myImage.src = 'https://www.google.com/logos/doodles/2017/holidays-2017-day-2-5240850203279360-s.png';
myImage.id = "myImageId";
myImage.onclick = myVerySpecialFunction();
document.body.appendChild(myImage);
var tmp = "myVerySpecialFunctionAnswer()";
document.getElementById("myImageId").setAttribute("onclick", tmp); }
function myVerySpecialFunction() { alert("Knock-knock!"); }
function myVerySpecialFunctionAnswer() { alert("Who is there!?"); }
When I add to my myImage.onclick function, it fired instantly. Why does it do that? Could I prevent it?
Of course, I can do a workaround here with setAttribute, but I don't like it.
https://jsfiddle.net/kv8w78be/3/