简体   繁体   中英

how do you trigger a function when more content is loaded onto a page, like tumblr and infinite scroll

Hi I'm writing a google chrome extension that redesigns tumblr for a project,

I'm trying to get rid of the 'notes' after the number of notes.

So far I have used this, except tumblr loads more posts as you scroll down and those don't get affected... :/

How would I trigger this function everytime more posts get loaded, or another way?

$('.note_link_current').each( function(index) {
  // Inside this function, "this" refers to the (DOM) element selected
  var text = $(this).text();
  /* ... */
});

Any help would be appreciated...

What you want is to run some piece of code over every node inserted into DOM filtered by class.

The modern way to do so is with DOM MutationObserver. Here's a canonical answer about it, and here's good documentation on it.

In a nutshell, here's what you should do:

function handleNote(element){
  var text = $(element).text();
  /* ... */
}

// Initial replacement
$('.note_link_current').each( function(index) { handleNote(this); });

var observer = new MutationObserver( function (mutations) {
  mutations.forEach( function (mutation) {
    // Here, added nodes for each mutation event are in mutation.addedNodes
    $(mutation.addedNodes).filter('.note_link_current').each(
      function(index) { handleNote(this); }
    );
  });
});

// Watch for all subtree modifications to catch new nodes
observer.observe(document, { subtree: true, childList: true });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM