Lieutenant Dan
Lieutenant Dan

Reputation: 8274

execute jquery code when user scrolls down a certain amount (pixels)

I would like to execute the below code when user scrolls to a certain position on the page; for instance 600px; down (from the top). So detect 600px down in PIXELS.

// $(document).ready(function() {
        $(".slidedown").one('load', function () {
            $(this).slideDown(200);
        }).each(function() {
          if(this.complete) $(this).trigger('load');
        });
// });

This did not work:

  $(document).scroll(function(){
      if (document.scrollHeight > 600) {
     $(".slidedown").one('load', function () {
        $(this).slideDown(200);
    }).each(function() {
      if(this.complete) $(this).trigger('load');
    });
   }
});

Upvotes: 0

Views: 686

Answers (2)

stackoverfloweth
stackoverfloweth

Reputation: 6917

simply set your threshold of # of pixels before you fire event and this function will be triggered when the user scrolls up or down by n pixels

https://jsfiddle.net/7daffjh8/7/

var scrollAmount = 0;
var pixelsToNotify = 200;

$(document).scroll(function() {
  var distance = $(window).scrollTop();
    console.log(distance, scrollAmount);
    if(distance - scrollAmount > pixelsToNotify){
        alert('user scrolled down event');
        scrollAmount = distance;
    }
    if(distance < scrollAmount - pixelsToNotify){
        alert('user scrolled up event');
        scrollAmount = distance;
    }
});

Upvotes: 2

Hacknightly
Hacknightly

Reputation: 5144

I think something like this will work

$(document).scroll(function(){
   if ($(document).scrollTop() > 600) {
     ... execute code
   }
});

https://jsfiddle.net/ga7140L9/1/

Upvotes: 0

Related Questions