views:

32

answers:

2

Here is the important part of my JS code:

function createClose() {
  var cButton = document.createElement("img");
  cButton.src = "close.gif";
  cButton.style.cursor = "pointer";
  cButton.onclick = closeWindow;

  document.getElementById("my_window").appendChild(cButton);
}

function closeWindow() {
  document.getElementById("my_window").style.display = "none";
}

The image gets created and appended, but there is no onClick event invoked when it is clicked. I also tried using an anonymous function, but that didn't work either.

No, I'm not going to use jQuery (although I believe you that it's easier).

+2  A: 
input = document.getElementById("my_window").appendChild(cButton);
input.onclick = function() { yourFunction(); };

This question is almost a duplicate of "Add onclick property to input with JavaScript" As an alternative way I've seen the use of input.setAttribute('onclick', 'yourFunction();'); too but cannot guarantee it works.

thisMayhem
Can I add the event handler before I append it to the document? As I said, anonymous functions didn't work in this case.
Khan
Take a look at the mentioned and linked question, they do that before appending it like you say (: Hope it helps
thisMayhem
the setAttribute() route worked for me, now I just need to check it for cross-browser compatibility...
Khan
Let me know once you try it out, so I don't have to test the cross-browser effectiveness myself, thanks.
thisMayhem
what does `input` refer to after line 1? what's the difference between line 2 and the onclick assignment in the question?
lincolnk
@lincolnk `input` is the name of the variable that will represent the element we will later append to "my_window". You could name that anything you want. And the difference is that instead of calling the function directly you call it through an anonymous function. Note the `function(){callToFunction();};`
thisMayhem
+1  A: 
input.setAttribute('onclick','handleClick();');
Christian Sciberras