1

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

Khan
  • 2,912
  • 3
  • 21
  • 21

2 Answers2

3
input.setAttribute('onclick','handleClick();');
Christian
  • 27,509
  • 17
  • 111
  • 155
2
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.

Community
  • 1
  • 1
Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
  • 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 Jun 16 '10 at 19:10
  • Take a look at the mentioned and linked question, they do that before appending it like you say (: Hope it helps – Juan Cortés Jun 16 '10 at 19:12
  • the setAttribute() route worked for me, now I just need to check it for cross-browser compatibility... – Khan Jun 16 '10 at 19:18
  • Let me know once you try it out, so I don't have to test the cross-browser effectiveness myself, thanks. – Juan Cortés Jun 16 '10 at 19:22
  • what does `input` refer to after line 1? what's the difference between line 2 and the onclick assignment in the question? – lincolnk Jun 16 '10 at 19:41
  • @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();};` – Juan Cortés Jun 17 '10 at 00:02