0

Let's say I have this piece of HTML code:

<a href="#">Plugin 1</a>
<a href="#" style="display:none">Plugin 1 options 1</a>
<a href="#" style="display:none">Plugin 1 options 2</a>
<a href="#">Header 2</a>
<a href="#" style="display:none">Plugin 1 options 1</a>
<div id="content"></div>

Whenever I click "Plugin 1" a table is generated inside Content div with headers containing "Plugin 1 options 1", "Plugin 1 options 2" etc. strings in them and the plugin options submenu have their "display" attribute turned to "block". I want to add an event listener to the "Plugin 1 options 1/2" elements so the page would scroll to the table header element with the same value.

How can I do that, as the elements of the table are created after the page is loaded?

Edit 1: It is not a problem of adding an event handler to not existing elements, as they are created at the very beginning. Problem here is that I want to add an event handler to existing element that will manipulate an element that will be created in the future. Here is an example from my code:

var table_element = $('th:contains("' + plugin_name + '")');
group_button.click(function () {
        table_element.get(0).scrollIntoView();
    });

group_button exists from the begging, where table_element is generated dynamically. Moreover, I checked whether $('th:contains("' + plugin_name + '")') is a correct selector, by passing it console when table was generated.

  • 1
    JS Event Delegation https://javascript.info/event-delegation – Clyde Lobo Feb 05 '19 at 15:20
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Clyde Lobo Feb 05 '19 at 15:20

2 Answers2

0

Since the event listener cannot manipulate the element until it is rendered, it is safe to assume, the action need only be performed once it has a value.

So, you could just use the selector inside the listener to get access to the DOM element instead of trying to store a reference of an element that could render in future.

group_button.click(function () {
    var table_element = $('th:contains("' + plugin_name + '")');
    if(table_element.get(0))
        table_element.get(0).scrollIntoView();
});

This way, if the element exists, it would be scrolled into view.

Dhananjai Pai
  • 5,397
  • 1
  • 6
  • 23
0

You need to make table_element local to event handler.

group_button.click(function () {
    var table_element = $('th:contains("' + plugin_name + '")');
        table_element.get(0).scrollIntoView();
    });
Tanmay
  • 1,012
  • 1
  • 10
  • 20