Calculating end of scroll on a web page - javascript

I need to calculate the end of scrolling on web page so that i can make an Ajax call.
I have searched posts in stackoverflow, but the solutions didn't worked for me.
I am using the below code ion order to determine that:
$(window).scrollTop() == $(document).height() - $(window).height()
but the above condition fails and am not able to get to know when page scroll ends.
As the values don't match on L.H.S and R.H.S the condition fails.
Just in order to check i used:
$(window).scrollTop() == $(document).height() - $(window).height() - 13
which works for chrome and firefox but fails for IE.
I need a concrete solution and don't want to hard code values.
Please help me in getting it right.
EDIT: To be specific, i am trying to calculate the end of vertical scroll bar.

Here is what I would do:
$(window).on('scroll', function() {
if($(window).scrollTop() != 0)
{
if( $(window).height() + $(window).scrollTop() >= $(document).height() )
{
//YES, I AM EXACTLY AT THE END OF THE SCROLL, PLZ FIRE AJAX NOW
}
}
});
CAUTION: Be very careful about having negative top margins though for styles in any of your elements on the page!! it may offset the calculation!

to calculate the end of scroll, try scrollHeight property.

This should retrieve the page height for you (not using jQuery but javascript instead):
var height = document.body.clientHeight;
You will find that this is the best cross-browser solution to your problem.

Here's how you do it. You take the scrolled distance and add the window height, then check if they equal the document height :
$(window).on('scroll', function() {
if (($(this).scrollTop() + $(this).height()) - $(document).outerHeight(true) >= 0) {
alert('Scrolled to bottom');
}
});
FIDDLE
This works for me in all five browsers!

Related

Perform action when object is visible in viewport

I have a div on my page, and I would like the background color to change when the viewer scrolls down to it.
How can I do this?
I would have used CSS3 with something like this...
var elemTop = $('div').offset().top;
$(window).scroll(function() {
if($(this).scrollTop() == elemTop) {
$('div').removeClass('hidden');
}
});
The commenter above is right. You should try something first and when you get stuck, the community will help you get unstuck. That said, here's a quick jquery to solve your problem.
$(document).ready(function(){
var offsetTop = $('#test').offset().top, //offset from top of element - element has id of 'test'
finalOffset = offsetTop - document.documentElement.clientHeight; //screen size
$(window).on('scroll',function(){
var whereAmI = $(document).scrollTop();
if(whereAmI >= offsetTop){
console.log("i've arrived at the destination");
}
})
})
Note that the above code executes the console.log() at every point past your requirement (meaning from there downwards). In case you want the execution to happen only one, you need to adapt the code a bit. One more note - if you're checking this in a fiddle, this document.documentElement.clientHeight needs to be adapted to work in an iframe. So test it on your local machine.

The most perplexing jquery issue i've ever run into

This very simple function to calculate the scroll of the page works just fine on jsfiddle, but I can't get it working on my page.
http://jsfiddle.net/SnJXQ/2/
The function is thus:-
jQuery(document).ready(function($) {
$(window).scroll(function() {
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
$('.bar-long').css('width', scrollPercent +"%" );
});
});
Simple, right? Thing is, it never applies the css to the bar-long class div on my local environment, just strange.
So I thought it might be an issue with window scroll function, so I done this:-
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
$(window).scroll(function() {
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
$('.bar-long').css('width', scrollPercent +"%" );
});
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("body").addClass("scrolled");
} else {
$("body").removeClass("scrolled");
}
});
});
Second function to test that I wasn't making an utterly stupid mistake, I wasn't, second function works just fine.
I'm running WordPress with their bundled version of jQuery1.11.1, hence the noconflict jQuery qualifier.
I even went as far as to paste in my entire css to jsfiddle along with a copy/pasta of my sites html, worked just fine.
I've disabled other scripts on the site, no conflict with those, no errors in console.
Just confused, really confused.
EDIT:- After some console logging;
console.log($(window).height());
console.log($(document).height());
console.log ($(document).height() - $(window).height());
=
5541
5541
0
So it thinks the window height and the document height are the same, which they are not. Hrmm.
I solved it.
Holy Christ almighty, it was because chrome gets confused with doctypes and thinks window/document height are the same if you mess that up, I was using this:
<!DOCTYPE html <?php language_attributes(); ?>>, I removed the php from it and now it works just fine.
Thanks to everyone that helped anyway. A good FYI, doctypes are important.
Based on your comment, it sounds like your code is trying to divide by zero.
If $(document).height() - $(window).height() is 0, you're doing 100 * $(window).scrollTop() / 0, which according to my firefox console comes out as Infinity.
You can't really set width: Infinity%; on an element, so check first! Something like this:
// Avoid a divide by zero error
var docHeight = $(document).height() - $(window).height();
if (docHeight < 1) {
docHeight = $(document).height();
}
var scrollPercent = 100 * $(window).scrollTop() / docHeight);
It's likely an overriding style
Try changing the class or enhancing the specificity of your selector $('.parent-div .bar-long'), etc.
Also, inspect the computed styles in your dev tools (Chrome inspector, Firebug, etc.) to see what styles in the cascade are being applied or overridden.

Scroll to certain height of a page javascript

I've a very simple one line code that checks whether user has scrolled to the bottom of the page, I want to change it a little bit & find whether user has reached the footer of the page. And height of footer is somewhat 350px.
Here's my code:
if($(window).scrollTop() + $(window).height() == ($(document).height())
{
...
}
This works like a charm (loads more content on scroll event), but if I do like this:
if($(window).scrollTop() + $(window).height() == ($(document).height()-350))
This doesn't work. When I attempt to alert('$(document).height()-350'). It gives a perfect alert.
Can anyone say what I'm doing wrong?
you are probably scrolling more than 1 pixel at a time and just skip the equality point. make it a >= and it should work:
if($(window).scrollTop() + $(window).height() >= ($(document).height()-350))
Try
if($(window).scrollTop() + $(window).height() >= $(document).height()-350)
Also you have '(' char in front of $(document).height() which needs to be removed
You want to use >= instead of ==, otherwise you must be pixel-perfect in your scroll in order for the event to fire.
Give this a try. You can use the .offset().top of your footer element to get the Y-position relative to the document.
var scrollBottom = $(window).scrollTop() + $(window).height();
var footerTop = $('#footer').offset().top; // change selector as needed
if ( scrollBottom >= footerTop ) {
alert("hello footer");
}

"infinite scroll" code working only for top scrolling

I'm using a "universal" piece of js that should detect if the user has scrolled to the bottom of the document:
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
//ajax code here
}
});
As the user scrolls, new content should load via the ajax call.
I would have expected the code to fire when I scroll DOWN, but the condition is actually firing when I scroll back to the TOP of the page, so it's basically doing the opposite of what it's "supposed" to do.
I've seen this solution being used in many examples, such as:
https://stackoverflow.com/a/17078097/1623095
My debugging messages:
console.log($(window).scrollTop());
console.log($(document).height());
console.log($(window).height());
These output when scrolling to the top:
0
1956
1956
And bottom:
961
1956
1956
The only plugin being loaded in my page is jquery (1.10.0.min), due to the nature of the project, I cannot link to the page.
Thoroughly confused by the dom behavior here.
I solved this some time before for someone else.
Have a look here:
Code
$(window).scroll(function () {
//- 10 = desired pixel distance from the bottom of the page while scrolling)
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
var box = $("#scrollbox");
//Just append some content here
box.html(box.html() + "<br />fa");
}
});
Fiddle
Just place your ajax code where I extended the content with simple html breaks

Event at the end of the document

I don't understand why this doesn't work. Explanation will be appreciated.
var scrollTop = $(window).scrollTop();
var height = $(window).height();
if (scrollTop === height ) {
alert("end!");
}
http://jsfiddle.net/Zasxe/
$(window).height() gives you the size of the user's viewport, not the size of the total document, which is what you most likely want. To find if the user has reached the end of the document, you've got to find the document's size, by $(document).height().
Furthermore, to find if a user's reached the end of the document, using jQuery, you need to capture the scroll event, and see if the user's reached the bottom:
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() === $(document).height()) {
alert("end!");
}
});
There's no event handler. That code only gets run once, when the page loads.
$(document).scroll(function () {
// Your code here
});
Be aware that the code will run every time you scroll, so don't make it to heavy.
And as someone else said, there were a number of other things wrong with the code - but start with putting the handler in.

Categories

Resources