Check all divs widths and resize any bigger than window - javascript

I have a blog with new responsive template. I want to check all divs inside the posts to get any that has width bigger than window size and change the width of ONLY those divs to have max-width: windowsize.
Truth is the blog has 350+ posts and I don't have time to edit every single post to remove the ones with divs with fixed width going offscreen.
I'm not very good with jQuery and js, but I got this code and got this far:
var div = $(".post div").width();
var win = $(window).width();
if (div > win ) {
$(" ONLY THE DIV THATS BIGGER? ").css('max-width', ' WINDOW-WIDTH? ');
}
But it's changing the size of ALL divs. Any ideas?
[SOLUTION - for my needs, anyway]
As much as all your jQuery codes were amazing, I couldn't get any of them to work on the divs I wanted (but I'm sure they'll help people seeing this post in the future), so I just went for basic CSS and it fits my needs. I was afraid of ruling ALL DIVS inside posts width:100% because it would affect the nested ones, so I just used:
.post-body > * {
max-width:100% !important;
}
It calls ONLY all direct children of my post, which is already the same size of the window on mobile, and sets the rule max-width to prevent going off the screen. Perfect!
Thank you for your help!

first of all you might want to start using a loop to go through all the divs thats being inside the variable "div" also dont try to immediately go after the width statement but get all the divs
so your code:
var div = $(".post div").width();
var win = $(window).width();
if (div > win ) {
$(" ONLY THE DIV THATS BIGGER? ").css('max-width', ' WINDOW-WIDTH? ');
}
should become something like this:
var div = $(".post div");
var win = $(window).width();
for(var i=0; i<div.length;i++){
if(div[i].width() > win){
$(div[i]).css('max-width','WINDOW-WIDTH?');
}
}
also if you want to find out what exactly div is use this code:
var div=$(".post div");
console.log(div);

try
var win = $(window).width();
$(".post div").each(function () {
if ( $(this).width() > win ) {
$(this).css('max-width', win );
}
});

The problem of overflow does not come from this. In fact, it comes from the div class linkwithin_inner where the width has been set to a fixed width of 680px !important.
You should change the width to 100% in the CSS found on that page.
.linkwithin_inner {
width: 100% !important;
}
and the problem will be solved out.

You'd need to filter out the divs that are wider than the window and then set max width to only those, like below.
var winWidth = $(window).width();
$(".post div").filter(function(){
return $(this).width() > winWidth
}).css({"max-width": winWidth + "px"});
Hers is a demo along the same lines

Basically you want to loop though all divs which are found by this `$(".post div")'
Which boils down to:
$(".post div").each(function () {
$(this).width("50px");
});
And here you have a working fiddle:
https://jsfiddle.net/gkLmx6d1/2/

Related

jQuery: How to get the dynamic height of header

I am new to jQuery. And I can't figure out the solution to this problem.
So, the problem is that I want a fixed header on my website. I did that with CSS. But I want to give the main container div(right below the header) a margin-top of the height of the header.
For example, if the #masthead (header) height is 100px, I want to give a margin-top of 100px to .site-container.
I can easily do it with CSS, but due to some reason, there will be different header height on different pages. Or let's suppose that I don't know the height of the header.
So I want to do it using jQuery.
Here is the code -
jQuery(document).ready(function($) {
var header = document.getElementById("masthead");
var header_height = header.offsetHeight + "px";
$( '.site-content' ).css( {
'margin-top': header_height
} );
});
It works perfectly. But there is just one problem.
That, the header height on my website changes in different screen size. In Desktop Screen size, the #masthead height is 80px, in tablet, the screen size is 160px and in mobile, it's 60px.
But, the value of header height does not change with the change in screen size in jQuery.
In jQuery, I want the value of the variable header to change dynamically, with the change in screen size.
Please note that I am working on a WordPress website.
Please help me.
Thank you.
Use:
Use a window resize function
You could also use: (to make your life easier :)
jQuery selectors
.outerHeight() to "Get the current computed outer height (including padding, border, and optionally margin)"
Example code:
jQuery(document).ready(function($) {
// When the window resizes
$(window).on('resize', function () {
// Get the height + padding + border of `#masthead`
var mastHeight = $('#masthead').outerHeight();
// Add the height to `.site-content`
$('.site-content').css('margin-top', mastHeight);
});
// Trigger the function on document load.
$(window).trigger('resize');
});
Write the same function on window.resize.
By the way, after resize the screen reload the page, hope your code will work as it will get the document ready function.
You can execute the same function on both page load and window resize.
jQuery(document).ready(function($) {
function resizeContent(){
var header = document.getElementById("masthead");
var header_height = header.offsetHeight + "px";
$( '.site-content' ).css( {
'margin-top': header_height
});
}
resizeContent();
$(window).resize(resizeContent);
});

jQuery element height calculation behaving unexpectedly

New to playing with jQuery and javascript (and stackOverflow). My project is basically a scrolling page with linked divs.
For aesthetic reasons, I wold like to have each div fill the size of window and I decided that jQuery would be an easy way to do this. The basic structure is this:
IF the div is shorter than the window
THEN grow to the size of the window.
ELSE use an auto height
I can get a single div to behave this way, the problem is I am applying this to a class and the other objects do not seem to want to behave in the same manner. Here is a fiddle (first time making a fiddle so if the link is not working let me know -
http://jsfiddle.net/ksaiyo/VBMVQ/3/
This fiddle shows the exact opposite:
http://jsfiddle.net/ksaiyo/6YYFU/1/
My script is here, but the fiddle seems to show the effect well enough. The heights stay at the auto height. (I have a fixed navigation header and unelegantly used padding on top so the linked elements in the page line up correctly - thus the extraneous variables)
$(document).ready(function() {
var divHeight = $( ".content" ).height();
var winHeight = $( window ).height();
var headerHeight = $( "header" ).height();
var viewHeight = winHeight - headerHeight
var newHeight = winHeight + headerHeight;
if (divHeight <= viewHeight ) {
$( ".content" ).height(newHeight);
};
)}
I have searched around and I can't seem to nail down the exact reason to why this is occurring. I tried to use an else statement in conjunction, but then everything including the small elements adopt the auto height. (I tried it in the fiddle as well)
Thanks in advance for your help.

Javascript function to find total page height

I'm after a simple javascript function that will detect the total height of my web page which is dynamic and apply it to the height of a div which is the page background. Would it be possible to implement it?
The div is called bg...
Any ideas? Thanks in advance
Try:
var height = body.offsetHeight ? body.offsetHeight : html.offsetHeight;
document.getElementById ('divID').style.height = height + 'px';
Here an useful documentation:
http://www.quirksmode.org/dom/w3c_cssom.html
Im using currently following code to do that:
var getBodyHeight = function () {
var d = document,
bd = d.body,
dd = d.documentElement,
max = Math.max(
bd.scrollHeight,
bd.offsetHeight,
bd.clientHeight,
dd.offsetHeight,
dd.scrollHeight,
dd.clientHeight
);
return max;
};
This is what I use to figure out the height of content in iFrame for the purpose of adjusting it properly.
var body = document.body,
html = document.documentElement,
height = 0;
height = body.offsetHeight;
if(height === 0){
height = html.offsetHeight;
}
The reason for checking the body first is that the height of html is actually the height of the iFrame, which could be bigger than the content itself. However, in certain cases such as when body has no height, then it falls back to use height of html instead.
For your case, you might want to experiment with a similar scheme. I'm not sure why you have to use a div to set background so I can't really suggest a better alternative (if any).
Solution based on the comment below:
What you can do is the following. Have a div inside the main container with position absolute, width/height 100% and z-index -1. Then it will always be the correct size no matter how large the contain grow or shrink. With this approach, you will have to make sure that container always has size. This is a pure CSS solution, which might be simpler than using Javascript to adjust.
var height = screen.height;
var width = screen.width;
var resolution = width+"x"+height;
alert(resolution);
it gives the resolution of the screen.i know you want page height and width but it will help you later in web development. i am using it as most important part for my web!

Animate DIV to full height and toggle back to defined height

I am trying to animate the div to its full height when a button is pressed and come back to its original height if the button is clicked again. The full height of the div is auto as it contains text with different word counts. I tried doing the below codes but it does not work properly.
The CSS :
.category_brief{
text-align:justify;
height:100px;
overflow:hidden;
}
Example 1 : This code does not animate the div when opening to full height , but animates while coming back to old height.
$(".slide").toggle(function(){
$('.category_brief').animate({height:'100%'},200);
},function(){
$('.category_brief').animate({height:100},200);
});
Example 2 : The output of this code is the same as of Example 1
var toggle = true, oldHeight = 0;
$('.slide').click(function(event) {
event.preventDefault();
var $ele = $('.category_brief');
var toHeight = ((toggle = !toggle) ? oldHeight : newHeight);
oldHeight = $ele.height();
var newHeight = $ele.height('auto').height();
$ele.animate({ height: toHeight });
});
Example 3 : This code animates the div to its full height but does not toggle.
var slide = $('.slide');
var slidepanel = $('.category_brief');
// On click, animate it to its full natural height
slide.click(function(event) {
event.preventDefault();
var oldHeight, newHeight;
// Measure before and after
oldHeight = slidepanel.height();
newHeight = slidepanel.height('auto').height();
// Put back the short height (you could grab this first
slidepanel.height(oldHeight);
slidepanel.animate({height: newHeight + "px"});
});
If possible please provide a bit explanation also as i am a newbie..
Update : Solved by the idea from #chazm..
#chazm : thanks for the idea. I got it working by combining 1st and 3rd example ... Here is the code in case anyone needs it .
var slidepanel = $('.category_brief');
$(".slide").toggle(function(){
var oldHeight, newHeight;
// Measure before and after
oldHeight = slidepanel.height();
newHeight = slidepanel.height('auto').height();
// Put back the short height (you could grab this first
slidepanel.height(oldHeight);
slidepanel.animate({height: newHeight + "px"})
},function(){
$('.category_brief').animate({height:100},300);
});
Working with 'auto' height it always quite tricky. I think there are different issues in your examples.
1) Browser can't define correct 100% height. Possible solutions - define height to all its parents. Either set it to 100% (till html tag) or set closest parent as relative (because height is calculated from closest relative parent). If you want to animate div to 100% of the entire page - think of the absolute positioning
2)The same as above i assume
3)When this code supposed to toggle back it can't determine that it should become lower that it is now. Not absolutely sure why though. Probably because 'auto' height from 100% is set to something wrong. You may check in firebug what value it has on the computed tab after that function is toggled back. Probably it will give you a clue
Try to combine 2) and 3). The idea - if toggle is true (it shoud be lowered) then set newHeight = slidepanel.height('100').
The solution depends on your implementation needs. If you know that at first the div should be 100px etc in height and when you click, it maximizes to an unknown height, the following solution would work. If you had a structure similar to
<div class="outer">
<div class="wrapper">Content of unknown length here</div>
</div>
and css
div.wrapper { position:relative; height:100px; overflow:hidden; }
div.outer { position:absolute; height:auto; }
then you'd get a div that is 100px in height, with the content that doesn't fit in 100px cut off. Now when you press the desired button, you could get the height of the wrapper div, since it is a long as it's content is (even though you only see the top 100px) and set the outer div's height according to it. Like so
var newHeight = $('div.wrapper').height();
$('div.outer').animate({height:newHeight},200);
Which would then animate the outer div to display the whole contents. When you click the button again, you could just do
$('div.outer').animate({height:'100px'},200);
And you would again have only the 100px height.

achieving equal height columns in a responsive / flexible layout

I'm trying to achieve equal height columns on a 'responsive' website.
That means I'm using media queries to provide several layouts for one website depending on the size of the device and window.
I have 2 columns which need to have the same height. It's easy to achieve when the layout is fixed. I found dozens of scripts that do it and it works well.
However when I resize the browser window, that generated height doesn't change. So if the window is smaller, the height of the columns stays the same as before and the contents of the columns overflows. It's ugly.
Is there a way that generated height could change as I resize the window ?
Note : because of what's inside the columns I cannot use any CSS trick with backgrounds images etc. I really REALLY need both columns to truly have the same height at all times.
This question is already pretty old, but I didn't stumble upon a good solution for this myself until now.
A working solution would be a jQuery plugin that does something like setting the height of the columns to 'auto', measuring which one is the highest and set the columns to that height. Something along the lines of this:
$.fn.eqHeights = function (options) {
var $el = $(this),
$window = $(window),
opts = $.extend({}, $.fn.eqHeights.defaults, options);
if ($el.length > 0 && !$el.data('eqHeights')) {
$(window).bind('resize.eqHeights', function () {
$el.eqHeights(opts);
});
$el.data('eqHeights', true);
}
return $el.each(function () {
var children = $(this).find(opts.childrenSelector);
if (!(opts.minWidth) || opts.minWidth < $window.width()) {
var curHighest = 0;
children.each(function () {
var $el = $(this),
elHeight = $el.height('auto').height();
if (elHeight > curHighest) {
curHighest = elHeight;
}
}).height(curHighest);
} else {
children.height('auto');
}
});
};
$.fn.eqHeights.defaults = {
childrenSelector: '*',
minWidth: ''
};
You can see this in action here: demo#codepen.io
The plugin supports two options:
childrenSelector: (Optional) The selector by which children that should get equal height are picked. Defaults to *, so everything in your parent is brought to equal height. Set to > to pick only direct children or something else to get the desired effect.
minWidth: (Optional) The minimum viewport width above width the Plugin is working and calculates equal heights for the seleted children. Below their height is set to auto. This comes in handy if at some point your containers are laid out below each other and shouldn't have an equal height. Empty and inactive by default.
While this is working very good in all browser with which I tested, it is a very hackish solution, so maybe someone here can propose something better. I thought about copying the columns and their wrapper to hidden container in the document, but this isn't any less clean and produces a way bigger footprint.
My favorite trick to creating equal height columns that work almost everywhere is to set "overflow:hidden" on a wrapper div, and setting a huge positive bottom padding and a negative bottom margin on the columns themselves. Now the columns will always be the full height of the wrapper, whatever the height of the wrapper is.
Viz -
<div class="wrapper">
<div class="column"> Column one content </div>
<div class="column"> Column two content </div>
</div>
<style type="text/css">
.wrapper {
overflow:hidden;
}
.column {
margin-bottom: -2000px;
padding-bottom: 2000px;
}
</style>
Here's a JSFiddle example - http://jsfiddle.net/yJYTT/
I wrote a small jQuery plugin for this: http://github.com/jsliang/eqHeight.coffee/
Tested it on Chrome, Firefox and IE9 and it works for me.
This works great! To make it work inside of a responsive layout you'll need to add the # media query so it's only used on screen sizes "larger than" your break point. Otherwise, the sidebar color extends down into the main content on the tablet and phone views. Here's how it looks in a responsive stylesheet:
div.wrapper {
overflow:hidden;
}
.column {
background-color: rgba(193,204,164,.5);
padding:2%;
margin-bottom: -2000px;
padding-bottom: 2000px;
}
#media screen and (max-width:960px){
.column {padding-bottom:2%; margin-bottom:0px;}
}
I hacked the solution even further from boundaryfunctions's answer to take into consideration responsive layouts where the panels reflow above each other.
By checking each one against the first one's offset.top I was able to detect the orientation of the panels and resize their .panel-body element or assign an auto heigh for reflowed panels.
(function($) {
$.fn.eqHeights = function() {
var el = $(this);
if (el.length > 0 && !el.data('eqHeights')) {
$(window).bind('resize.eqHeights', function() {
el.eqHeights();
});
el.data('eqHeights', true);
}
var panels = el.find(".panel-body");
var fistoffset = panels.first().offset();
var curHighest = 0;
return panels.each(function() {
var thisoffset = $(this).offset();
var elHeight = $(this).height('auto').height();
if(thisoffset.top==fistoffset.top){
if (elHeight > curHighest) {
curHighest = elHeight;
}
}else{
curHighest = "auto";
}
}).height(curHighest);
};
}(jQuery));
$('.match_all').eqHeights();
Example here: http://bootply.com/render/104399
Some time after the question I know - but for reference - last time I had to solve this problem I hacked this jquery code to a plugin:
http://css-tricks.com/equal-height-blocks-in-rows/
obviously $(window).resize is the crucial part - as it'll re-conform the heights once the re-size has taken place. Taking it a step further I always meant to look into 'de-bouncing' the column reconform to help with performance:
http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
but never got that far.
I had the same problem. After some research I selected the faux column technique. Check this blog post that I wrote on how to make it work in a responsive design.
Responsive full height (equal height) columns using the faux columns technique

Categories