dsp_099
dsp_099

Reputation: 6121

Javascript: How to check if something's been added to DOM?

Take a look at this site. When you scroll down, it automatically loads up a bit more of the page. Say that I have an event that runs on document.load. Is there a way to make it do that again when you scroll down and more stuff comes into view?

It's worth mentioning that I'm trying to design a way to sort of catch all instances like this, not just the specific site I mentioned which may very well have something to latch onto when it's doing the infinite scrolling.

Upvotes: 0

Views: 226

Answers (2)

chrisfrancis27
chrisfrancis27

Reputation: 4536

The behaviour you're describing is often referred to as "infinite scrolling".

EDIT: My answer above doesn't really answer your question.

The closest I can think of for a truly generic way of handling this, even when it's not your code that is adding elements to the DOM, is to use the DOM Level 3 API Mutation events, but they are now deprecated and should not be used.

There is ongoing work on a proposal for mutation observers in DOM Level 4, but these are not yet standardised. However, take a look at this article for an example implementation.

Upvotes: 0

apsillers
apsillers

Reputation: 115940

There are deprecated DOM3 Mutation Events, like DOMSubtreeModified, which fire whenever specific mutation event occur. For performance and compatibility reasons, MDN strongly discourages their use, but they do exist. I also believe that they don't provide information about what kind of mutation has occurred or any kind of before/after comparison.

There's a W3C draft for DOM4 Mutation Observers, which might be implemented in some browsers currently. I know it's at least implemented in Chrome, which uses WebKitMutationObserver like so:

var observer = new WebKitMutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

There's a full list of mutation properties in the draft (scroll down to the green box).

Upvotes: 1

Related Questions