Get height of the div on window resize - javascript

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
}

Related

jQuery to dynamically resize divs

I'm using the media thumbnails that twitter bootstrap v2.3 has in their CSS library. You can see what I'm working on here.
Here is the jQuery I'm using:
<script>
$(window).load(function () {
var maxHeight = 0;
var divs = jQuery(".thumbnail");
jQuery.each(divs, function () {
var height = jQuery(this).height();
if (maxHeight < height) maxHeight = height;
});
divs.css('min-height', maxHeight + 'px');
});
$(window).resize(function () {
var maxHeight = 0;
var divs = jQuery(".thumbnail");
jQuery.each(divs, function () {
var height = jQuery(this).height();
if (maxHeight < height) maxHeight = height;
});
divs.css('min-height', maxHeight + 'px');
});
</script>
Basically my goal was since each thumbnail had different heights and I wanted them to all be equal heights, this script gives them all the same min-height in CSS on load, and everytime the screen is resized based on whichever thumbnail has the greatest height.
I got all that to work, but now the problem I can't figure out is when you drag the screen to smaller/bigger sizes and the min-height becomes very large, I have no code to decrease the min-height so they thumbnail divs look way too big. Does anyone have any code suggestions for me so the divs will all have equal height, but never get too big?
And if you set the height css property rather than min-height, the solution doesn't work for my original goal because the text paragraphs end up extending outside the divs.
On window resize you can set the min-height of the divs again, like this:-
$( window ).resize(function() {
if($( window ).height() < 300){
$( "div" ).css({min-height: 300px});
} else {
$( "div" ).css({min-height: 600px});
}
});

Equal height divs (or li) in rows with fluid width and height

I found this sweet jQuery snippet by CSS-Tricks' Chris Coyier that resets div elements heights that share the same top position on the page (are on the same row) to the tallest element.
The Problem
This solution almost works with fluid width layouts and resets height when top positions changes but it resets it to the original height of the current tallest element in the row when the page first loaded. This is an issue because the height of the tallest element might have changed since this page first loaded because of the use of relative units like ems or because of word wrapping with paragraphs.
Proposed Solution
The solution would be to have the row's elements' height being set to the tallest element's current height, not the original height. I have been unsuccessful in accomplishing this.
Here is the snippet where "li.half" is the elements being compared and resized.
jQuery(document).ready(function($) {
// these are (ruh-roh) globals. You could wrap in an
// immediately-Invoked Function Expression (IIFE) if you wanted to...
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array();
function setConformingHeight(el, newHeight) {
// set the height to something new, but remember the original height in case things change
el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")));
el.height(newHeight);
}
function getOriginalHeight(el) {
// if the height has changed, send the originalHeight
return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"));
}
function columnConform() {
// find the tallest DIV in the row, and set the heights of all of the DIVs to match it.
$('li.half').each(function() {
// "caching"
var $el = $(this);
var topPosition = $el.position().top;
if (currentRowStart != topPosition) {
// we just came to a new row. Set all the heights on the completed row
for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);
// set the variables for the new row
rowDivs.length = 0; // empty the array
currentRowStart = topPosition;
currentTallest = getOriginalHeight($el);
rowDivs.push($el);
} else {
// another div on the current row. Add it to the list and check if it's taller
rowDivs.push($el);
currentTallest = (currentTallest < getOriginalHeight($el)) ? (getOriginalHeight($el)) : (currentTallest);
}
// do the last row
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest);
});
}
$(window).resize(function(){
columnConform();
});
// Dom Ready
// You might also want to wait until window.onload if images are the things that
// are unequalizing the blocks
$(function() {
columnConform();
});
});
Please let me know if you can figure out how to make the setConformingHeight adjust on window resize.
Those solutions didn't work on window.resize() as elements height should be unlocked with $el.height('auto') before calculating new real height.
Here is my solution :
var currentRowTop = -100, currentHighest= 0;
$('.page-wrapper .cc').each(function() {
$el=$(this);
if($el.position().top!=currentRowTop){
equalizeHeight();
currentRowTop = $el.position().top;
$el.height('auto').addClass('same-height');
currentHighest=$el.height();
}else{
$el.height('auto').addClass('same-height');
currentHighest = ($el.height()>currentHighest) ? $el.height() : currentHighest ;
}
});
equalizeHeight();
function equalizeHeight(){
if($('.same-height').size()==0) return;
$('.same-height').height(currentHighest).removeClass('same-height');
}

Window width and resize

I would like to calculate the number of icons e.g. 50px depending on the width of the window for a menu.
So I started with:
$(window).width();
While loading the page with document ready function the width will be given. OK!
Now I would calculate the right amount of icons while resize the window.
$(window).resize(function() {
//resize just happened, pixels changed
});
Tasks
Initial width of the window -> if user is not resizing the window
Variable width of the window -> if user is resizing the window
Each task is running but i donĀ“t get it together.
Can u help me --> THX!!
How can i calculate the number of icons with an initial width of the window and while resizing the window?
My Start:
var activeItemcount;
checkWidth();
$(window).resize(checkWidth);
function checkWidth() {
windowSize = $(window).width();
// console.log(windowSize);
var activeItemWidth = '100'; // width of the icons
var maxWidth = windowSize; // max div width on screen
activeItemcount = maxWidth / activeItemWidth; // max icon with actual screen width
activeItemcount = Math.round(activeItemcount) -1; // calculation
console.log(activeItemcount);
var i = '0';
$('.platform-view').each(function(){
if(i < activeItemcount ){
$(this).wrapAll('<div class="iconview-1" />');
i++;
}else{
$(this).wrapAll('<div class="iconview-2" />');
}
});
};
I didn't get you clearly.
but this code will return the variable width of the windows while resizing.
Jquery:
$(window).resize(function() {
$('#log').append('<div>'+$(window).width()+'</div>');
});
HTML:
Example:
A sample of the code
Place your calculation into its own function:
function calculateIcons()
{
var viewport = { width: $(window).width(), height: $(window).height() };
// Do cool things with viewport.width
}
And then you can simply bind this function to the DOMReady and resize functions in jQuery as follows:
$(calculateIcons);
$(window).resize(calculateIcons);

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.

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.

Categories

Resources