nico_lrx
nico_lrx

Reputation: 280

How to call javascript function each time user scrolls

I want to call a javascript function each time Facebook updates their feed for a user (when he scrolls). Any idea how I can do that?

This does not work:

if (document.body.scrollTop > 30) {
        addArt();
}

Thank you

Upvotes: -1

Views: 12206

Answers (3)

Captain Squirrel
Captain Squirrel

Reputation: 237

Using jquery, you can use this function to run code every time the user scrolls

$( window ).scroll(function() { $(window).scrollTop() > 30) { addArt(); } });

window.onscroll = function() { if (document.body.scrollTop > 30) { addArt(); } };

edit: added none jquery version

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You need to attach it to the window's scroll event listener. I have wrapped it inside an onload event, so that it gets executed after the document is loaded.

window.onload = function () {
  window.onscroll = function () {
    if (document.body.scrollTop > 30) {
      addArt();
    }
  };
};

Or if you are using jQuery, use:

$(function () {
  $(window).scroll(function() {
    if (document.body.scrollTop > 30) {
      addArt();
    }
  });
});

Upvotes: 2

tymeJV
tymeJV

Reputation: 104775

Using an onscroll function:

window.onscroll = function() { }

Upvotes: 7

Related Questions