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.
Related
For a parallax-effect, I created a simple script in native Javascript, but it seems to fail somewhere I can't see. That's why I already added the requestAnimationFrame-functionality, but it doesn't seem to really help.
My relevant code is as follows:
var $parallax, vh;
$(document).ready(function() {
$parallax = $('.parallax');
vh = $(window).height();
$parallax.parallaxInit();
});
$(window).resize(function() {
vh = $(window).height();
$parallax.parallaxInit();
});
$.fn.parallaxInit = function() {
var _ = this;
_.find('.parallax-bg')
.css('height', vh + (vh * .8) );
}
//call function on scroll
$(window).scroll(function() {
window.requestAnimationFrame(parallax);
});
var parallaxElements = document.getElementsByClassName('parallax'),
parallaxLength = parallaxElements.length;
var el, scrollTop, elOffset, i;
function parallax(){
for( i = 0; i < parallaxLength; i++ ) {
el = parallaxElements[i];
elOffset = el.getBoundingClientRect().top;
// only change if the element is in viewport - save resources
if( elOffset < vh && elOffset + el.offsetHeight > 0) {
el.getElementsByClassName('parallax-bg')[0].style.top = -(elOffset * .8) + 'px';
}
}
}
I think it's weird that this script by Hendry Sadrak runs better than my script (on my phone) while that is not really optimised, as far as I can tell.
Update: I checked if getBoundingClientRect might be slower in some freak of Javascript, but it's about 78% faster: https://jsperf.com/parallax-test
So here is the downlow on JS animations on mobile devices. Dont rely on them.
The reason is that mobile devices have a battery and the software is designed to minimize battery load. One of the tricks that manufacturers use (Apple does this on all their mobile devices) is temporarily pause script execution while scrolling. This is particularly noticeable with doing something like parallax. What you are seeing is the code execution - then you scroll, it pauses execution, you stop scrolling and the animation unpauses and catches up. But that is not all. iOS uses realtime prioritization of the UI thread - which means, your scrolling takes priority over all other actions while scrolling - which will amplify this lag.
Use CSS animation whenever possible if you need smooth animation on mobile devices. The impact is seen less on Android as the prioritization is handled differently, but some lag will likely be noticeable.
Red more here: https://plus.google.com/100838276097451809262/posts/VDkV9XaJRGS
I fixed it! I used transform: translate3d instead, which works with the GPU instead of the CPU. Which makes it much smoother, even on mobile.
http://codepen.io/AartdenBraber/pen/WpaxZg?editors=0010
Creating new jQuery objects is pretty expensive, so ideally you want to store them in a variable if they are used more than once by your script. (A new jQuery object is created every time you call $(window)).
So adding var $window = $(window); at the top of your script and using that instead of calling $(window) again should help a lot.
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.
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.
Sorry in advance if this is a minor question, but I'm new to javascript. I'm writing code for a webpage with full-width color backgrounds. Essentially, what I'm trying to do is detect the height of the window, and then make sure that the color block is the size of the window. The function works well on page load.
The problem is when I shrink the window, the div height doesn't change with the window size. I get all sorts of errors, like graphics poking out from behind the div.
I think what I'm missing is a way to detect the height of the content within each div and resize the height accordingly.
You can see how it works at http://pressshoppr.com
Here's the code:
$(function(){
var windowH = $(window).height();
if(windowH > wrapperH) {
$('.fullWidthSectionBG').css({'height':($(window).height())+'px'});
$('.fullWidthSectionBGFirst').css({'height':($(window).height())-120+'px'});
}
$(window).resize(function(){
var windowH = $(window).height();
var wrapperH = $('.fullWidthSectionBG').height();
var newH = wrapperH + differenceH;
var truecontentH = $('.fullWidthSection').height();
if(windowH > truecontentH) {
$('.fullWidthSectionBG').css('height', (newH)+'px');
$('.fullWidthSectionBGFirst').css('height', (newH)-120+'px');
}
});
});
I am not sure I totally understand the effect you are going for here, but I would imagine that if your initial bit of code achieves it, all you have to do is reuse exactly that. Treat each resize as if the page had just loaded, and get the results you want, eg:
$(function(){
// encapsulate the code that we know WORKS
function init() {
var windowH = $(window).height();
if(windowH > wrapperH) {
$('.fullWidthSectionBG').css({'height':($(window).height())+'px'});
$('.fullWidthSectionBGFirst').css({'height':($(window).height())-120+'px'});
}
}
// call on page ready
init()
// ...and call again whenever the page is resized
$(window).resize(init)
});
I'm trying to counteract an adjustment to the height of an element which is above the scroll offset by calculating the difference in height and then updating the current scroll position to account for it.
The problem is that there's no way that I can prevent a very quick flickering artefact. Whether I adjust the element's height and then the scroll position, or vice versa, I can't seem to prevent a quick visual jump.
Does anyone know how this could be overcome? I want these to operations to happen at the same time with no rendering in-between but I'm not sure if it's possible.
// Setup
...
var myElement = ...
var oldHeight = ...
var scrollOffset = window.scrollY;
var newHeight = 100;
var diff = newHeight - oldHeight;
// Determine if we need to counteract new size
var adjustScroll = (absoluteOffset(myElement) < scrollOffset);
// Adjust size
myElement.style.height = newHeight+'px';
// Adjust scroll to counteract the new height
if (adjustScroll) window.scrollTo(0, scrollOffset+diff);
I'm working with WebKit, specifically on iOS.
for webkit you can use CSS transitions/animations to smooth this but it's still sound like you are going the wrong way to begin with. I am sure that whatever is it you are trying to do can be solved purely with CSS (maybe with some very minimal Javaqscript). Post an example of you HTML + CSS + JS.
You could use scrollIntoView with timers to simulate multiple threads.
Or you could do it inside a document fragment beforehand.
Sorry to be reviving an old post here, but i came across this looking for a solution to a similar problem to do with browser resizing.
Stackoverflow user James Kyle created this little jsfiddle using jQuery that attempts to maintain scroll position as best as possible when a page is resized
var html = $('html'),
H = html.outerHeight(true),
S = $(window).scrollTop(),
P = S/H;
$(window).scroll(function() {
S = $(window).scrollTop();
P = S/H;
});
$(window).resize(function() {
H = html.outerHeight(true);
$(window).scrollTop(P*H);
});
http://jsfiddle.net/JamesKyle/RmNap/
you could try using this same code and trigger a 'resize' event on the html when the image has loaded by using a jQuery library like imagesLoaded