0

I am having issues adding a click event listener to elements that are not yet present on the page. Just a note that I am performing the following code within a JQuery equavilant to document ready, so it is performed after the DOM is loaded. So I have a div which I am using as a type of button

<div id="openContainer"> ... </div>

Now when this div is clicked, another div is dynamically added to the page. This div is only added when the above click event takes place. The div that is added has a button with the id search. I am trying to add an event listener to this. So far I have this

document.getElementById('openContainer').addEventListener('click', function() {
    document.getElementById('search').addEventListener('click', function() {
        alert("ADDED")
    });
});

However when I run this I get an error that document.getElementById(...) is null. I think the reason behind this is because the event listener is being added before the actual dynamic div has been added. In fact, I know this is the case because it works with a timeout e.g.

document.getElementById('openContainer').addEventListener('click', function() {
    setTimeout(function () {
       document.getElementById('search').addEventListener('click', function() {
           alert("ADDED")
       });
    }, 2000);
});

Is there any way I can do this without a timeout?

Thanks

katie hudson
  • 2,765
  • 13
  • 50
  • 93

2 Answers2

1

You can place a single event-handler on the existing element, and in the anonymous function of addEventListener(), check the id of the element upon which the event was triggered:

document.getElementById('openContainer').addEventListener('click', function(event){
  var clicked = event.target;
  if (clicked.id === 'openContainer') {
    // the '#openContainer' element was clicked,
    // ...do stuff
  } else if (clicked.id === 'search') {
    // the '#search' element was clicked,
    // ...do stuff
  }
});
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • The only problem with that is that it still shows the error because the search element is not yet present – katie hudson Feb 14 '17 at 13:46
  • Can you show enough of your code that we can reproduce your problem? The approach posted shouldn't generate any errors, since if the element with the id of `"search"` doesn't exist it won't enter the `else if` branch that requires it. – David Thomas Feb 14 '17 at 14:01
0

One possible reason is that your JavaScript is running before the DOM element is even created.

Make sure your script tags are after the tags.

devDeejay
  • 5,494
  • 2
  • 27
  • 38