Jorre
Jorre

Reputation: 17591

detect distance scrolled from top jquery

How can I detect the number of pixels scrolled in a browser window? I need this to dynamically adjust the height of a 100% height div...

I'm using jQuery.

EDIT: I cannot just use scrollTop() because I'm working with a 100% height div with overflow set to auto. Firefox does not detect browser scrolling due to this, the only thing scrolling is a 100%x100% div...

Upvotes: 44

Views: 81738

Answers (4)

fruitloaf
fruitloaf

Reputation: 2930

$(document).ready(()=> {
  $(window).scroll(function() {
    console.log($(window).scrollTop());
  })
}

Upvotes: 1

thecraighammond
thecraighammond

Reputation: 850

You can use scrollTop() to find out how far down the page you've traveled.

$(window).scroll(function() {
  console.log($(window).scrollTop());
  if ($(window).scrollTop() > 200) {
    $('#div').stop().animate({
      'marginTop': $(window).scrollTop() + 'px',
      'marginLeft': $(window).scrollLeft() + 'px'
    }, 'slow');
  }
});

Upvotes: 9

Jorre
Jorre

Reputation: 17591

Allright guys, I found it:

$("div#container").scroll(function() {
         var screenheight = parseInt($(document).height());
         var scrolledpx = parseInt($("div#container").scrollTop());     
         var sum = screenheight+scrolledpx;
         console.log($("div#container").scrollTop());
         console.log("screen: " + screenheight);
         console.log("sum=" + sum);
         $("div.content").height(sum);
})

Upvotes: 7

David Hellsing
David Hellsing

Reputation: 108520

use $(document).scrollTop() :

$(document).scroll(function() {
    console.log($(document).scrollTop());
})

Upvotes: 85

Related Questions