Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for specific elements to load?

Is it possible to listen for a specific DOM element to be loaded? I have a window.onload event that is called when the whole page loads, but I'm looking for a way for it to be called for each DOM element that gets loaded. (Does onload not bubble up?)

Example:

function init() {
  alert(this.id); // Should be in context of DOM element that bubbled up when loaded
}
window.onload = init;
<div id="one">One</div>
<div id="two">One</div>
<div id="three">One</div>

I want this code to alert one, two, three.

like image 470
Matt Avatar asked Oct 15 '25 16:10

Matt


1 Answers

onload events don't bubble like this, you have 2 options here:

  1. poll for the element, running a check for it on an interval.
  2. use DOM mutation events (which vary across browsers - mainly IE implementation headaches) to listen, though this will be expensive, since you'll have to filter everything other than your element.
like image 168
Nick Craver Avatar answered Oct 18 '25 07:10

Nick Craver