Different height of element depending on page load - javascript

i'm developing a site where i use jQuery to achieve a faux columns effect. Here is a test page: http://goo.gl/IL3ZB . The left yellow <aside> height is set in java script with the height of the .body_container div. The height is set correctly for display.
The problem is when i do in Firefox 17 a full refresh (Shift + F5) the <aside> is displayed correctly, with the correct height, but the animation in js sees a much smaller height. When i then refresh the page normally, then java script also sees the correct height.
How can i resolve this problem?
Here is my js:
var floating_patents_bottom = 0;
$(window).load(function(){
$('.floating_patents').height( $('.body_container').height() );
floating_patents_bottom = ($('.body_container').height() > floating_patents_bottom ? $('.body_container').height() : floating_patents_bottom);
var toBottom = {
'top': floating_patents_bottom
};
});
var toTop = {
'position': 'absolute',
'top': '500px',
'display': 'none'
};
$(document).ready(function(){
$('.floating_patents').height( $('.body_container').height() );
floating_patents_bottom = ($('.body_container').height() > floating_patents_bottom ? $('.body_container').height() : floating_patents_bottom);
// floating_patents_bottom = $('.floating_patents').height();
var toBottom = {
'top': floating_patents_bottom
};
var patents = $(".floating_patents img");
patents.css(toTop);
patents.each(function(index) {
$(this).delay(index * 5000).css('margin','10px auto').fadeIn("slow").animate(toBottom , 15000, function(){
$(this).fadeOut("slow");
});
});
});

The problem is that when handler $(document).ready is called your images in content aren't fully loaded and have zero dimensions, so your $('.body_container').height() calculated incorrectly (the calculations sometimes happens correctly when browser takes images from the cache). The easiest solution for you is to move all code inside $(window).load handler.
A little refactored code which will work:
function floatingPatents() {
// find required elements in DOM
var patentsBlock = $('.floating_patents'), bodyContainer = $('.body_container');
var patents = patentsBlock.find('img').hide();
var floating_patents_bottom = 0;
// wait for complete page load
$(window).load(function(){
// resize holder
floating_patents_bottom = bodyContainer.height();
patentsBlock.height( floating_patents_bottom );
// calculate offsets
var toTop = {
position: 'absolute',
top: '500px',
display: 'none'
};
var toBottom = {
top: floating_patents_bottom
};
// start animation
patents.show().css(toTop).each(function(index) {
$(this).delay(index * 5000).css('margin','10px auto').fadeIn("slow").animate(toBottom , 15000, function(){
$(this).fadeOut("slow");
});
});
});
}
// run code when page ready
$(floatingPatents);

The document is ready before all of its elements are loaded. You're getting the correct height on the $(window).load event, but you're initializing the animations in the $(document).ready event. Just move everything into $(window).load and you should be good.
If waiting for the window to finish loading is too long (since otherwise, you won't be able to get the proper height of your .body-container div), you might be able to try this technique for getting placeholders for your images, so that the flow is correct before they've actually loaded.
http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/

Related

Prevent triggering windows resize event when css property is changed using jquery

I have added a windows resize event on my page
it is called whenever page size is changed.
but when I update css values for a div element inside page using jquery css and animate it automatically triggers windows resize event.
this happens only for IE
I want to prevent resize event from executing on manual change of size by animate or css methods
Here is my code
for window resize
window.onresize=function(){ ... };
for div size change
$('div#divtest').css({ 'position': 'absolute', 'z-index': '1', 'background-color': '#f6f6f6' }).animate({
width: '20%',
height : $('div#divother').height() - 29
}, 0);
EDIT:
i do not want to make any change in resize event reason is it is page wise different so i have to make change in all existing events
any chance i can temporary turn it off
You can achieve this by following way:
Before applying css animation set some flag like following:
$('div#divtest').data("css_animation", true); //set the flag
$('div#divtest').css({ 'position': 'absolute', 'z-index': '1', 'background-color': '#f6f6f6' }).animate({
width: '20%',
height : $('div#divother').height() - 29
}, 0,function() {
// Animation complete.
$('div#divtest').data("css_animation", false); //reset the flag
});
And in resize we can check whether flag is set or not as follows:
window.onresize=function(){
var flagValue = $('div#divtest').data("css_animation"); //fetch the flag value
//don't do anything if resize is getting called via css animation
if(flagValue === true)
return;
...
};
Finally i solved this.
thanks to vijayP for flag suggestion.
but instead of puting flag in each resize function i just override window.onresize function
i add following code in master page script /general script
(function($) {
var oldresize = window.onresize;
window.onresize = function() {
if (CallPageResize)
return oldresize.call(this);
};
})(jQuery);
where CallPageResize is flag and its value is set as follow
CallPageResize = false; $('div#divtest').css({ 'position': 'absolute', 'z-index': '1', 'background-color': '#f6f6f6' }).animate({
width: '20%',
height: $('div#divother').height() - 29
}, 0);
CallPageResize = true;
To avoid unnecessary window resize event, compare the previous window width and height and proceed the window resize event if width or height differs. This is only a workaround solution.
private previousWindowWidth = 0; private previousWindowHeight = 0;
private onWindowResize(): void {
var windowWidth = window.innerWidth;
var windowHt = window.innerHeight;
if (previousWindowWidth === windowWidth && previousWindowHeight ===
windowHt ) {
return;
}
previousWindowWidth = windowWidth ;
previousWindowHeight = windowHt ;
// continue with other operations
..................................
}

Add pixels to existing CSS element with Javascript

here is my trouble.
I'm using a plugin for a lightbox. For some reason, one of the divs is 28px too short. I've looked all over for a solution for this, but nobody seems to be having the same problem.
The solution I've come up with is to find that element (which I have) and create a javascript snippet that will add "28" to the existing number. The height and width is being calculated directly on the div, not in an element in a stylesheet.
Example:
<div id="colorbox" class="" style="padding-bottom: 57px; padding-right: 28px; position: absolute; width: 892px; height: 602px; top: 2234px; left: 500px;">
I want the Javascript code to add 28 pixels to the width and 55px to the height.
How would I go about doing this?
I would like to say that I'm not looking for just an answer; if you could explain it to me, that would be great. Thanks so much, guys!
Edit: this is how I called the JQuery
Also, this is where you can see the page with the gallery: http://olsencustomhomes.com.previewdns.com/designs/verona-2/#gallery
EDIT FOR KRIS:
Is this the right code? It's in my header
<script>
$(document).ready(function() {
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}
$(document).ajaxStop(function() {
changeSize();
});
});
</script>
Pretty straightforward application of jQuery, but I commented it up for you anyway:
//select the box element using jQuery
var box = $('#colorbox');
//get the current width and height
var curWidth = box.width();
var curHeight = box.height();
//set the width and height with modified values
box.width(curWidth + 28);
box.height(curHeight + 55);
fiddle: http://jsfiddle.net/579s2/
If you want to add height and width dynamically. Something like this should work:
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}changeSize();
Also if you want to insure your code is happens after the colorbox opens you could use .ajaxStop(); Also note, outerWidht() and outerHeight() will get colorbox width plus the padding and borders.
To fire function after ajax events are finished:
$(document).ajaxStop(function() {
changeSize();
});
Update:
Okay, it looks the function fires initially. You can see width is null because the colorbox has not opened. What you want to do is fire the function after the colorbox opens. That is where ajaxStop() would come into play. But it might actually be better to use the colorbox callback function:
But not after the colorbox opens. So try doing the ajaxStop() approach. Also note, if you do this you will need to remove changeSize(); after function changeSize() For example:
$(document).ready(function() {
function changeSize(){
// function stuff
}
$(document).ajaxStop(function() {
changeSize();
});
});
Or, Colorbox OnComplete:
$(".selector").colorbox({
onComplete:function(){
changeSize();
}
});
Update 2:
I am not sure where you are calling colorbox exactly. But I see you have this: Found here
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%'
});
});
So try:
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%',
onComplete:function(){
changeSize();
}
});
});

Do not execute jQuery script if CSS is of particular value

On my website, I have a sidebar DIV on the left and a text DIV on the right. I wanted to make the sidebar follow the reader as he or she scrolls down so I DuckDuckGo'ed a bit and found this then modified it slightly to my needs:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
$window.scroll(function(){
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
})
});
});//]]>
</script>
And it works just like I want it to. However, my website uses Skeleton framework to handle responsive design. I've designed it so that when it goes down to mobile devices (horizontal then vertical), sidebar moves from being to the left of the text to being above it so that text DIV can take 100% width. As you can probably imagine, this script causes the sidebar to cover parts of text as you scroll down.
I am completely new to jQuery and I am doing my best through trial-and-error but I've given up. What I need help with is to make this script not execute if a certain DIV has a certain CSS value (i.e. #header-logo is display: none).
Ideally, the script should check for this when user resizes the browser, not on website load, in case user resizes the browser window from normal size to mobile size.
I imagine it should be enough to wrap it in some IF-ELSE statement but I am starting to pull the hair out of my head by now. And since I don't have too much hair anyway, I need help!
Thanks a lot in advance!
This function will execute on window resize and will check if #header-logo is visible.
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
});
I think you need to check this on load to, because you don't know if the user will start with mobile view or not. You could do something like this:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
// Your code
}
}).resize();
This will get executed on load and on resize.
EDIT: You will probably need to turn off the scroll function if #header-logo is not visible. So, instead of create the function inside the scroll event, you need to create it outside:
$(window).resize(function() {
if ($('#header-logo').is(':visible')) {
var $sidebar = $('#sidebar'),
sidebarOffset = $sidebar.offset(),
$window = $(window),
gap = $('#header').css('marginBottom').replace(/[^-\d\.]/g, ''),
distance = ($window.scrollTop()) - (sidebarOffset.top - gap),
footerHeight = $('#footer').outerHeight();
function myScroll() {
distance = ($window.scrollTop()) - (sidebarOffset.top - gap);
if ( distance > 0 ) {
$sidebar.css({'top': gap + 'px', 'position' : 'fixed'});
} else {
$sidebar.css({'top': '0', 'position': 'relative'});
}
}
$window.on('scroll', myScroll);
} else {
$(window).off('scroll', myScroll);
}
});
Didn't test it, but you get the idea.
$("#headerLogo").css("display") will get you the value.
http://api.jquery.com/css/
I also see you only want this to happen on resize, so wrap it in jquery's resize() function:
https://api.jquery.com/resize/

unexpected behaviour: absolute positiong & $(window).resize()

I am using a absolute positioned layout (a bit similar to pinterest)
So I need to recalculate positions also on window.resize: And as this event is not fired on dom ready, I do it manually.
$(document).ready(function(){
$(window).resize();
});
$(window).resize(setupBlocks);
Now, this function setupBlocks checks for the sizes of the HTML elements to calculate its new position
function setupBlocks() {
if ($('.fancyContent').length > 0) {
if ($('.rightFixed').length > 0) $('.fancyContent').width($(window).width() - 320)
windowWidth = $('.fancyContent').width();
//colWidth = $('.fancyContent .widgetHelp').outerWidth();
blocks = [];
//console.log(blocks);
colCount = Math.floor(windowWidth / (colWidth + margin * 2));
for (var i = 0; i < colCount; i++) {
blocks.push(margin);
}
$('.fancyContent .widgetHelp').css({
'position': 'absolute',
'width': colWidth
});
positionBlocks();
var topFooter = $('.fancyContent .widgetHelp:last').offset().top + 350;
$('footer').css({
'position': 'absolute',
'top': topFooter
});
//console.log(topFooter);
$('.fancyContent').css('visibility', 'visible');
$('#load').remove();
//console.log($('#load').length);
}
}
function positionBlocks() {
$('.fancyContent .widgetHelp').each(function () {
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin + (index * (colWidth + margin));
$(this).css({
'left': leftPos + 'px',
'top': min + 'px'
});
blocks[index] = min + $(this).outerHeight(true) + margin;
});
}
The unexpected thing is that this is executed as expected. But the positions are not very well calculated untill the window is resized. Then the positions become exact.
I know it's a long shot. but any idea why it could be behaving differently?
Its better if you test yourself: http://209.51.221.243/integracion/login.php
When the page is load, the divs are almost fine (some of them are vertically touching), but if you resize the div the divs get well positioned. any thougths?
When you write:
$(document).ready(function(){
$(window).resize();
});
setupBlocks function isn't called, this way it is:
$(document).ready(function(){
$(window).on('resize', setupBlocks); // window listens for resize events
$(window).resize(); // fire window resize
});
Now you are sure your setup is run at page load [fiddle].
Rather than running the $(window).resize() on document ready, run it on window load. In other words change
$(document).ready(function(){
$(window).resize();
});
to
$(window).load(function(){
$(window).resize();
});
Since document ready just waits until all the DOM elements are in place, jQuery can't detect the proper block sizes and positions, because the images aren't loaded. Once the images load, dimensions change. If you want to get things positioned ASAP, try specifying heights and widths for the images, so when the document is ready (rather than the window loaded), jQuery can pick up on all the image sizes.

lock a div on header when window scrolled past element

I want a circle div to lock in the header when the user scrolls past in.
I'm using the following code but it doesn't work
var circle$ = $('.circle'),
oCircleBottom = circle$.offset().top + circle$.outerHeight(true),
window$ = $(window);
window$.scroll(function() {
if (window$.scrollTop() > oCircleBottom) {
}
}.bind(this));
I want to perform an action when the user scrolls pass the circle div; however, the code above does not seem to work. Is oCircleBottom computed correctly?
Enclose your code in $(document).ready function
$(document).ready(function () {
var circle$ = $('.circle'),
oCircleBottom = circle$.offset().top + circle$.outerHeight(true),
window$ = $(window);
window$.scroll(function () {
if (window$.scrollTop() > oCircleBottom) {
$('.circle').css({
position: 'fixed',
top: '0',
left: '0'
});
}
else{
$('.circle').css({
position: 'static'});
}
}.bind(this));
});
You need to take window height into account because if the height of the page isnt enough to scroll down, your code doesnt work. Take a look at this example
However, if the increase page height, you code will work fine without subtracting window height. Take a look at this example
Hence, its better to subtract the window height. jsFiddle
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('.circle').offset().top + $('.circle').innerHeight() - window.innerHeight) {
//Do you stuff
}
});

Categories

Resources