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.
Related
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.
I have a page that I need to dynamically load ajax content when the user scrolls to the bottom. The problem is that JQuery is not returning the correct window height. I have used this function before and have never seen it fail, but for some reason it will return the same value as the document height. I have the test page here: bangstyle.com/test-images
I have coded the alert to display at page load, and also whenever the user scrolls 500px below the top:
function scroller() {
if($(window).scrollTop() > 500){
delay(function(){ //200ms wait
pagecounter++;
sideshow();
alert("window height: " + $(window).height() + " scrolltop: " + $(window).scrollTop() + " document height: " + $(document).height());
return false;
}, 200 );
}
}
I tried posting this before but I deleted it as I didn't get a solution. I hope it is ok to post a link to my test page. BTW I have tested this on Mac Safari and Mac FF. I have run this same code on other pages and it works fine. I feel there must be something in the dom of this page that causes JS to fail, but no idea what that would be.
Look at your HTML souce code.
The first line should be <!DOCTYPE html> and you have <style> tag instead.
So it seems that your document is running in Quirks Mode and jQuery can't calculate correct window dimensions.
//works in chrome
$(window).bind('scroll', function(ev){
//get the viewport height. i.e. this is the viewable browser window height
var clientHeight = document.body.clientHeight,
//height of the window/document. $(window).height() and $(document).height() also return this value.
windowHeight = $(this).outerHeight(),
//current top position of the window scroll. Seems this *only* works when bound inside of a scoll event.
scrollY = $(this).scrollTop();
if( windowHeight - clientHeight === scrollY ){
console.log('bottom');
}
});
I had the same problem.
I've found some things:
1) the problem happens when you try to get the actual height before document is completed rendered;
2) the problem happens in google chrome when you does not use corret DOCTYPE (mentioned above)
3) it always happens in google chrome even after the document is rendered completly.
For google chrome, I've found a workaround here: get-document-height-cross-browser
I'm using this solution only for google chrome and it resolved my problem, I expect helps someone that still have the problem.
This is an old question but I recently struggled with not getting the correct window height in IE10 by a few pixels.
I discovered that IE10 applies a 75% zoom by default and that screws the window and document measurements.
So, if you're getting wrong width or height, make sure zoom is set to 100%.
Did some looking around and stumbled upon this, don't know if it helps but it's worth bringing up.
why is $(window).height() so wrong?
Since jquery (and dom in general) is not calculating sizes correctly in quirksmode, two solutions:
Add doctype html at the top of your page (like mentioned in "correct" answer), or
Use window.innerHeight, window.innerWidth if first option is not an option.
Hope it helps.
I moved my scripts from to footer and that resolved it for me.
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!
I have some code that depends on the css being loaded.
I load css on the header before I load the javascripts on the footer
I tried the javascript with $(document).ready
$(document).ready(function() {
var bar_position, width;
bar_position = $('body').height() - 38;
width = $('body').width();
console.log(bar_position);
if (width <= 480) {
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
I tried $(window).ready, $(window).load, but all of them fail.
You code is really messed up (unless you are using CoffeeScript.) This is what it should be:
$(function () {
bar_position = $('body').height() - 38; //38 is the size of the bar
width = $('body').width();
console.log(bar_position);
if (width <= 480) { //480 is the mobile width
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
With CSS being loaded in the header, JS in the footer, and wrapped in a doc-ready, you should be fine as far as the CSS being applied before the JS code is executed. I'm guessing the reason your element has no width is that it is display: none;, or contains only floated elements, or something along those lines. In other words - I think this is a CSS issue, not a JS timing issue. Try going into your Firebug/Chrome console, selecting the element in question, and getting its width.
JavaScript comments are not #, they are //
wrong
bar_position = $('body').height() - 38 #38 is the size of the bar
right
bar_position = $('body').height() - 38 //38 is the size of the bar
And there are a bunch of other errors where that code would not run. Guessing you missed a tag and this is not pure JavaScript since it is indented for block scope and missing braces/closures all over.
The ready event should suffice.
When using scripts that rely on the value of CSS style properties,
it's important to reference external stylesheets or embed style
elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the
dimensions of an image are required), the code should be placed in a
handler for the load event instead.
Also, your javascript is invalid. If it is supposed to be CoffeeScript, you are missing ->:
$(document).ready ->
bar_position = $('body').height() - 38 #38 is the size of the bar
width = $('body').width()
console.log(bar_position)
if (width <= 480) #480 is the mobile width
console.log("Entered");
$('#accounts-bar').css("top", bar_position)
return
If it's supposed to be JavaScript, you have more issues:
$(document).ready(function(){
bar_position = $('body').height() - 38; //38 is the size of the bar
width = $('body').width();
console.log(bar_position);
if (width <= 480) //480 is the mobile width {
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
$(window).bind("load", function() {
// code here
});
The following code crashes IE6 every time. It keeps refreshing the page and crashes after a minute:
$(window).bind("load resize", function () {
var hnf = $('#header').height() + $('#footer').height();
$('#main').height($(window).height() - (hnf));
$('.fluid').height($('#main').outerHeight());
$('#content').width($('#main').width() - $("#aside").width() - 90);
});
..whats causing it?
EDIT: Okay the "resize" in $(window).bind("load resize", function () { is causing it, how do I fix?
Many thanks for your help!
It looks as though IE6 incorrectly fires the onResize event even when the document body dimensions change. Here's a link with more information.
I would look for a non-jQuery way to do what you want. If you use CSS to control the fixed-size elements of your page, won't the browser take care of the variable-size elements on its own?
The fix Drew Wills links to sounds like it should work. Try:
var prevHeight;
$(window).bind("load resize", function () {
var height = $(window).height();
if ( prevHeight == height )
return; // hack to prevent recursion in IE6
prevHeight = height;
// resize content
var hnf = $('#header').height() + $('#footer').height();
$('#main').height(height - (hnf));
$('.fluid').height($('#main').outerHeight());
$('#content').width($('#main').width() - $("#aside").width() - 90);
});
Feel free to pretty that up a bit (attach prevHeight to something else, etc).
I think it might have to do with the fact that you are trying to set the height and width without CSS. I am not sure but if I was going to do it I would use the JQUERY .css() method to set he height and width. so it would look like this,
$(window).bind("load resize", function () {
var hnf = $('#header').height() + $('#footer').height();
$('#main').css("height", ($(window).height() - hnf));
$('.fluid').css("height", ($('#main').outerHeight()));
$('#content').css("width", ($('#main').width() - $("#aside").width() - 90));
});
This might not work I did not test it.