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

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.

Related

Get height of the div on window resize

I have a function that resizes divs depending on how high (in pixels) other divs with the same class are:
<script type="text/javascript">
function resizeTheDivs(tag){
// first get the tags to adjust
var $tags = $('.' + tag);
var $new_height = 0;
// find out which one is largest
$('.' + tag).each(function(){
$(this).height() > $new_height ? $new_height = $(this).height() : null;
});
// make all others that height
$tags.height($new_height);
// I console.log($new_height) here sometimes
}
// resize divs on document load
$(document).ready(function(){
resizeTheDivs('the-class');
});
// resize divs on window resize
$(window).resize(function () {
resizeTheDivs('the-class');
});
</script>
The divs resize correctly on page load, but when console.log($new_height) fires from the window resize function, the $new_height is not changed.
Context: There are 3 divs (floated left, so next to each other with 33% width) that contain text in p tags. So when I resize the browser width, the text gets 'longer', but the javascript function isn't picking up the new heights of the divs.
Any ideas?
You need to reset the height to auto before measuring it, or else it will always return the fixed value you set in $(document).ready:
function resizeTheDivs(tag){
// first get the tags to adjust
var $tags = $('.' + tag);
var $new_height = 0;
// find out which one is largest
$('.' + tag).each(function(){
$(this).removeAttr('style');
$(this).height() > $new_height ? $new_height = $(this).height() : null;
});
// make all others that height
$tags.height($new_height);
// I console.log($new_height) here sometimes
}

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/

Different height of element depending on page load

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/

how to re-calculate variables in javascript

function scrollContent(){
var div = $('#scrolling-content'),
ul = $('ul.image'),
// unordered list's left margin
ulPadding = 0;
//Get menu width
var divWidth = div.width();
//Remove scrollbars
div.css({overflow: 'hidden'});
//Find last image container
var lastLi = ul.find('li:last-child');
//When user move mouse over menu
div.mousemove(function(e){
//As images are loaded ul width increases,
//so we recalculate it each time
var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
div.scrollLeft(left);
});
}
This is how I scroll my image list. The problem is that #scrolling-content element's size is dynamic. It changes on window resize. Here;
$(window).resize(function() {
$("#scrolling-content").css("width",$(window).width() + "px");
$("#scrolling-content").css("height",($(window).height()-400) + "px");
});
So it has to recalculate the left value when user changes windows size. How sould I change script to do that? Recalling scrollContent() function with window.resize function is a noob solution I guess. And it creates conflict for IE.
You could set the width on resize and make your function call the variable like so. This method turns your function into a js object and the window update resets the width var inside that object. Course now you call the function like this: scrollContent.scroll();
var scrollContent = {
width: 0,
scroll:function(){
var div = $('#scrolling-content'),
ul = $('ul.image'),
// unordered list's left margin
ulPadding = 0;
//Get menu width
scrollContent.width = div.width();
//Remove scrollbars
div.css({overflow: 'hidden'});
//Find last image container
var lastLi = ul.find('li:last-child');
//When user move mouse over menu
div.mousemove(function(e){
//As images are loaded ul width increases,
//so we recalculate it each time
var left = (e.pageX - div.offset().left) * (ulWidth-scrollContent.width) / scrollContent.width;
div.scrollLeft(left);
});
}
};
$(window).resize(function() {
$("#scrolling-content").css("width",$(window).width() + "px");
$("#scrolling-content").css("height",($(window).height()-400) + "px");
scrollContent.width = $(window).width();
});
You can also just declare a standard js var and use that to keep things simple. I just prefer working with js objects to eliminate possible var interference.

How do I get an element to scroll into view, using jQuery?

I have an HTML document with images in a grid format using <ul><li><img.... The browser window has both vertical & horizontal scrolling.
Question:
When I click on an image <img>, how then do I get the whole document to scroll to a position where the image I just clicked on is top:20px; left:20px ?
I've had a browse on here for similar posts...although I'm quite new to JavaScript, and want to understand how this is achieved for myself.
There's a DOM method called scrollIntoView, which is supported by all major browsers, that will align an element with the top/left of the viewport (or as close as possible).
$("#myImage")[0].scrollIntoView();
On supported browsers, you can provide options:
$("#myImage")[0].scrollIntoView({
behavior: "smooth", // or "auto" or "instant"
block: "start" // or "end"
});
Alternatively, if all the elements have unique IDs, you can just change the hash property of the location object for back/forward button support:
$(document).delegate("img", function (e) {
if (e.target.id)
window.location.hash = e.target.id;
});
After that, just adjust the scrollTop/scrollLeft properties by -20:
document.body.scrollLeft -= 20;
document.body.scrollTop -= 20;
Since you want to know how it works, I'll explain it step-by-step.
First you want to bind a function as the image's click handler:
$('#someImage').click(function () {
// Code to do scrolling happens here
});
That will apply the click handler to an image with id="someImage". If you want to do this to all images, replace '#someImage' with 'img'.
Now for the actual scrolling code:
Get the image offsets (relative to the document):
var offset = $(this).offset(); // Contains .top and .left
Subtract 20 from top and left:
offset.left -= 20;
offset.top -= 20;
Now animate the scroll-top and scroll-left CSS properties of <body> and <html>:
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});
Simplest solution I have seen
var offset = $("#target-element").offset();
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
}, 1000);
Tutorial Here
There are methods to scroll element directly into the view, but if you want to scroll to a point relative from an element, you have to do it manually:
Inside the click handler, get the position of the element relative to the document, subtract 20 and use window.scrollTo:
var pos = $(this).offset();
var top = pos.top - 20;
var left = pos.left - 20;
window.scrollTo((left < 0 ? 0 : left), (top < 0 ? 0 : top));
Have a look at the jQuery.scrollTo plugin. Here's a demo.
This plugin has a lot of options that go beyond what native scrollIntoView offers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.
You can also have a look at all the JQuery plugins tagged with "scroll".
Here's a quick jQuery plugin to map the built in browser functionality nicely:
$.fn.ensureVisible = function () { $(this).each(function () { $(this)[0].scrollIntoView(); }); };
...
$('.my-elements').ensureVisible();
After trial and error I came up with this function, works with iframe too.
function bringElIntoView(el) {
var elOffset = el.offset();
var $window = $(window);
var windowScrollBottom = $window.scrollTop() + $window.height();
var scrollToPos = -1;
if (elOffset.top < $window.scrollTop()) // element is hidden in the top
scrollToPos = elOffset.top;
else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
if (scrollToPos !== -1)
$('html, body').animate({ scrollTop: scrollToPos });
}
My UI has a vertical scrolling list of thumbs within a thumbbar
The goal was to make the current thumb right in the center of the thumbbar.
I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.
markup:
<ul id='thumbbar'>
<li id='thumbbar-123'></li>
<li id='thumbbar-124'></li>
<li id='thumbbar-125'></li>
</ul>
jquery:
// scroll the current thumb bar thumb into view
heightbar = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar = $('#thumbbar').scrollTop();
$('#thumbbar').animate({
scrollTop: offsetthumb.top - heightbar / 2 - offsetbar - 20
});
Just a tip. Works on firefox only
Element.scrollIntoView();
Simple 2 steps for scrolling down to end or bottom.
Step1: get the full height of scrollable(conversation) div.
Step2: apply scrollTop on that scrollable(conversation) div using the value
obtained in step1.
var fullHeight = $('#conversation')[0].scrollHeight;
$('#conversation').scrollTop(fullHeight);
Above steps must be applied for every append on the conversation div.
After trying to find a solution that handled every circumstance (options for animating the scroll, padding around the object once it scrolls into view, works even in obscure circumstances such as in an iframe), I finally ended up writing my own solution to this. Since it seems to work when many other solutions failed, I thought I'd share it:
function scrollIntoViewIfNeeded($target, options) {
var options = options ? options : {},
$win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
$container = options.$container ? options.$container : $win,
padding = options.padding ? options.padding : 20,
elemTop = $target.offset().top,
elemHeight = $target.outerHeight(),
containerTop = $container.scrollTop(),
//Everything past this point is used only to get the container's visible height, which is needed to do this accurately
containerHeight = $container.outerHeight(),
winTop = $win.scrollTop(),
winBot = winTop + $win.height(),
containerVisibleTop = containerTop < winTop ? winTop : containerTop,
containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
containerVisibleHeight = containerVisibleBottom - containerVisibleTop;
if (elemTop < containerTop) {
//scroll up
if (options.instant) {
$container.scrollTop(elemTop - padding);
} else {
$container.animate({scrollTop: elemTop - padding}, options.animationOptions);
}
} else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
//scroll down
if (options.instant) {
$container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
} else {
$container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
}
}
}
$target is a jQuery object containing the object you wish to scroll into view if needed.
options (optional) can contain the following options passed in an object:
options.$container - a jQuery object pointing to the containing element of $target (in other words, the element in the dom with the scrollbars). Defaults to the window that contains the $target element and is smart enough to select an iframe window. Remember to include the $ in the property name.
options.padding - the padding in pixels to add above or below the object when it is scrolled into view. This way it is not right against the edge of the window. Defaults to 20.
options.instant - if set to true, jQuery animate will not be used and the scroll will instantly pop to the correct location. Defaults to false.
options.animationOptions - any jQuery options you wish to pass to the jQuery animate function (see http://api.jquery.com/animate/). With this, you can change the duration of the animation or have a callback function executed when the scrolling is complete. This only works if options.instant is set to false. If you need to have an instant animation but with a callback, set options.animationOptions.duration = 0 instead of using options.instant = true.

Categories

Resources