Khan
Khan

Reputation: 2982

How can I add an onclick handler on a dynamic element?

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

Upvotes: 1

Views: 6582

Answers (2)

Juan Cortés
Juan Cortés

Reputation: 21072

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.

Upvotes: 2

Christian
Christian

Reputation: 28125

input.setAttribute('onclick','handleClick();');

Upvotes: 3

Related Questions