Is there a way to attach event handlers to an HTML element as soon as the element is present on the page


I do not want to wait till the whole HTML DOM is ready. Note that I’m not talking about dynamically loaded HTML elements. I’m talking about element which are in the HTML but not rendered yet.


Three ideas:

  1. Use an attribute in the HTML like onclick="foo()". This will be in force immediately.

  2. You could place a <script> tag immediately after the HTML element embedded in the HTML and have that script add the event handler. All DOM elements located before a script are guaranteed to be parsed and ready.

  3. You could make the element by initially hidden (either inline style specification or CSS), then wait until it’s in the DOM, run your script to install the event handler and then make the object visible. If you use visibility: hidden, then the document will lay out as normal and the content can be made visibility: visible after installing the event handler.

The browser doesn’t offer access to the object until it’s parsed and in the DOM so any script that wants to operate on it has to either be physically located after the DOM element or has to wait for an event to occur that indicates the DOM has been loaded.

The browser doesn’t offer an event when a DOM element is parsed, but not yet visible that would offer you a chance to operate on it at that moment so you have to work around your issue with one of these other methods.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published