How to detect scroll position of page using jQuery
I am having trouble with jQuery functionality on my website. What it does, is that it uses the window.scroll()
function to recognize when the windows changes its scroll position and at the change calls a few functions to load data from the server.
The problem is the .scroll()
function is called as soon as there is even a little change in the scroll position and loads data at the bottom; however, what I wish to achieve is to load new data when the scroll/page position reaches at the bottom, like it happens for Facebook feed.
But I am not sure how to detect scroll position using jQuery?
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
//Load some data from the server
})
};
$(window).scroll(function () {
getData();
});
You can extract the scroll position using jQuery's .scrollTop()
method
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
// Do something
});
You are looking for the window.scrollTop()
function.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > some_number) {
// do something
}
});
Check here DEMO http://jsfiddle.net/yeyene/Uhm2J/
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
//Load some data from the server
})
};
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
// getData();
}
});
$(window).scroll( function() {
var scrolled_val = $(document).scrollTop().valueOf();
alert(scrolled_val+ ' = scroll value');
});
This is another way of getting the value of scroll.
Now that works for me...
$(document).ready(function(){
$(window).resize(function(e){
console.log(e);
});
$(window).scroll(function (event) {
var sc = $(window).scrollTop();
console.log(sc);
});
})
it works well... and then you can use JQuery/TweenMax to track elements and control them.