jQuery detecting scroll- scroll reaching to the bottom of page

jQuery detecting scroll- scroll reaching to the bottom of page

Detecting scroll and executing login based on scrolling has important significance in web development like implementing pagination, where more data gets loaded when user scrolls near the bottom of page.

So, first basic question arises as to how to detect scroll.

window.onscroll = function(ev) {
	    //execute your logic here
	}
};

OR, if you are a jQuery freak, you can use-

$(window).scroll(function(){
       //execute your logic here
});

Now, how to detect that the scroll has reached to the end of page.

$(window).scroll(function(){
       if(jQuery(window).scrollTop()==jQuery(document).height() -jQuery(window).height()){
		alert("Vallah!!! You scrolled to the end of page");
	}
});

A quick suggestion. Note that our logic was to detect end of page scrolling. However, if you are implementing pagination where you want to load more data, then do not start your AJAX load when scrolling reaches end. Good design is to start the loader when the scroll is near to end of page.

$(window).scroll(function(){
       if(jQuery(window).scrollTop()>jQuery(document).height()-jQuery(window).height()-500){
		//start your AJAX loading
	}
});

Leave a Reply

Your email address will not be published. Required fields are marked *