0

Hi I just created a table dynamically, its working fine, but I need a on click on imageId. So what I did is:

document.getElementById("imageId").addEventListener("click", function () {    
    alert("hello");    
});  

but it is not working, I don't need any jquery only using JavaScript.

The code creating table dynamically is given below and it is working fine.

var body = document.body,
    tbl = document.createElement('table'),
    tableId = document.createAttribute('id');

tbl.style.width = '100%';

for (var i = 0; i < 3; i++) {
    var tr = tbl.insertRow();
    tr.style.height= '40px';
    var timetd = tr.insertCell();
    var tdcompany = tr.insertCell();
    var chatsymbol = tr.insertCell();
    var amounttd = tr.insertCell();
    tdcompany.innerHTML = "abc";
    timetd.innerHTML = "ss";
    chatsymbol.innerHTML = '<img  src=\'images/iproseIcon2.png\' width= "35%" margin-top="10px"; >';
    amounttd.innerHTML = total  + '<img id="imageId" src=\'images/iconarrowright.png\' >';
} 
Monasha
  • 711
  • 2
  • 16
  • 27
manu padmanabhan
  • 59
  • 1
  • 1
  • 8
  • My guess is that the `addEventListener` is called before your image is added to the DOM. To be sure we need to know the execution order of you code snippets. – BetaRide Nov 04 '16 at 10:44
  • another pattern to try is adding your event listener to a parent element (which is already on the page) instead of directly adding it to the img itself. – Sgnl Nov 04 '16 at 10:48
  • There already was similar question and the problem was solved. See [the question](http://stackoverflow.com/questions/14258787/add-event-listener-on-elements-created-dynamically) – Sebastian Kaczmarek Nov 04 '16 at 10:55

2 Answers2

0

If you try with this code:

var myElement = document.getElementById("imageId");
if (myElement) {
      document.getElementById("imageId").addEventListener("click", function () {

   alert("hello");

}); 
} else {
    alert("Element does not exist yet");
}

you will see an alert telling you that the element does not exist yet. You need to make sure that when you try to add the handler the element exists. You can use a load handler for that purpose.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

Try these i hope it will work for dynamical images it is working for me. in place of 'img_id' give the id of those images click will work fine.

$('#img_id').on('click', function () {
             alert("Image Success");
    });