jQuery Find height of the largest element - javascript

I have six divs that all need to be the height as the one with the largest height.
For example if one div has 5 lines of text in it, and the others all have 2, then they all need to stretch to match the height of the one with 5 lines.
How can I do this by the elements' classes?

var mh=0;
$(".some-class-name").each(function () {
if (mh < $(this).height()) {
mh=$(this).height()
}
})
$(".some-class-name").height(mh);

$(document).ready(function(){
var el = $('.one'),
elHeight = [];
el.each(function(){
elHeight.push($(this).height());
});
el.height(Math.max.apply(Math, elHeight));
});
http://jsbin.com/qovacanari/1/edit?html,js,console,output

Related

Combining Similar If Statements In Javascript

I'm using JS with similar if statements in order to have Divs side by side. As the topic title suggests, can these if statements be combined or made more efficient in any way?
EDIT: The purpose of this code is to make all Divs the same height.
JS:
$(document).ready(function(){
$('.container').each(function(){
var firstDiv = $(this).find('.first');
var secondDiv = $(this).find('.second');
var thirdDiv = $(this).find('.third');
var fourthDiv = $(this).find('.fourth');
if(firstDiv.height() >= secondDiv.height()){
secondDiv.css('height',firstDiv.height());
} else {
firstDiv.css('height',secondDiv.height());
}
if(secondDiv.height() >= thirdDiv.height()){
thirdDiv.css('height',secondDiv.height());
} else {
secondDiv.css('height',thirdDiv.height());
}
if(thirdDiv.height() >= fourthDiv.height()){
fourthDiv.css('height',thirdDiv.height());
} else {
thirdDiv.css('height',fourthDiv.height());
}
});
});
Test page: http://www.gloryhood.com/articles/ztest.html
As the intention of the code is to equalise the heights of all the divs, you can negate the need for any if statements and use jQuery's map() to get all the heights, then use Math.max to get the tallest. Try this:
$('.container').each(function(){
var $divs = $('.first, .seconds, .third, .fourth', this);
var heights = $divs.map(function() {
return $(this).height();
}).get();
$divs.height(Math.max.apply(this, heights));
});
Note that the initial selector could be improved by adding a single common class to all the divs.
If your aim is to make all the heights the max height of any, the current code will not work (unless the first div is tallest).
Solution: check the heights for the max height first, then apply that height to them all.
$(document).ready(function () {
$('.container').each(function () {
var $divs = $('.blah', this);
var height = 0;
$divs.each(function(){
height = Math.max($(this).height(), height);
});
$divs.css('height',height);
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/8hko6of7/1/
Notes
I do not use your class names, but instead a common class on all the divs.
If your aim was something else, please explain in more detail :)

jQuery addClass only to div with class which is really higher

The code below causes that all divs with this class get padding including these divs which are not higher than 200, but I need to add padding ONLY to elements, which are really bigger than 200. The rest have to stay without padding. Does anybody know how I can get it?
var n = $('.class');
var height = n.height();
if (height > 200) {
n.addClass('padding');
}
Use .filter to select just the elements with the height you want:
$(".class").filter(function() {
return $(this).height() > 200;
}).addClass("padding");
In your code, n.height() just returns the height of the first element selected, it doesn't change what n refers to in the n.addClass() call.
Use each() function to iterate over the .class elements and check each height.
Then apply .padding class to those who's height is higher that 200px:
$('.class').each(function() {
var that = $(this);
if (that.height() > 200) {
that.addClass('padding');
}
});

How to find width of inner elements

I couldn't find any other questions asking the same thing, though that may be a problem with my search phrasing.
I'm trying to figure out how to find the largest width of all elements contained inside of a container div with a fixed width. So, in the image below, the black box is the container div with a fixed width. The red box represents the contents of the container div, which are subject to change. I want to find the width of the red box, using only the black box in js.
Here is a jsfiddle with what I've been working on/trying:
http://jsfiddle.net/w87k5/1/
the current jquery functions I've tried, with no success:
.width();
.innerWidth();
.outerWidth();
.scrollLeft();
Note: I do not know ANYTHING about the contents of this container. They could be any html element or mix of html elements, from divs to imgs to iframes. I could put a "red box" without a fixed width surrounding them. Overflow of the black box will be hidden.
Update: There could be any number of children in the container. Like this: http://jsfiddle.net/w87k5/3/
Update 2: I'm going to run benchmark speed tests on all of the answers to see which one is the fastest, and select one after that. Thanks for all your input!
Benchmarks:
I generated 1000 divs with a random width of inbetween 0 and 100, recorded the Date().getTime(), did the test, then recorded time again. Here are the results:
~2418 avg. milliseconds with the for loop for length. I might have messed this one up somehow?
for (var i = 1; i <= count; i++){
var q = $("#box :nth-child(" + i + ")").width();
if(q > box){
box = q;
}
}
~34.4 avg. ms for the .each loop.
~22.4 avg. ms for the .map function. (Chosen answer.)
If you need all nested elements can search with * selector which will return all descendent elements:
var widthArray=$('#box *').map(function(){
return $(this).outerWidth();
}).get();
var maxWIdth= Math.max.apply(Math, widthArray);
For just children:
var widthArray=$('#box').children().map(function(){....
You could use .each() to cycle though each child element.
jsFiddle example
var widths = [];
$('#box').children().each(function(i){
widths[i] = $(this).width();
});
alert(Math.max.apply(Math, widths));
Which will return the width of the child element with the largest width.
Get the number of children, and loop through to get the width of each
$(document).ready(function () {
var count = $("#box").children().length;
var h = 0;
for (var i = 1; i <= count; i++) {
max = $("#box :nth-child(" + i + ")").width();
var h = Math.max(max, h);
}
alert(h);
});
http://jsfiddle.net/JDVN3/1/
Please not that the index starts from 1 and not 0.
Check out: http://api.jquery.com/nth-child-selector/

Access contents of div elements based on their window position

I have two div elements on my page which are positioned in such a way that both divs are at the same distance from the top of the page but are separated by some horizontal distance. Both div elements have some text entered into them dynamically using Javascript/jQuery. I want to access the text within the two divs in such a way that I can perform some action when both divs contain the same (or matching) text. Is there a way to do this based on the position of the divs using Javascript/jQuery ? I cannot use the obvious solution of id's because of certain restraints.
Lets say that the two divs you want are at 100, 100 and 100, 300 :
var all_divs = $("div");
var div1;
var div2;
for (var i=0; i<all_divs.length; i++){
var o = $(all_divs[i]).offset();
if (o.top == 100 && o.left == 100) {
div1 = all_divs[i];
}
if (o.top == 100 && o.left == 300) {
div2 = all_divs[i];
}
}
var polling = setInterval(function(){
if ($(div1).text() == $(div2).text()) {
perform_some_action();
clearInterval(polling);
}
}, 500);
If you're looking to identify your divs based on their position use .offset()
-Api documentation for .offset()

dynamic calculation of li height

I have the following code
The issue is that currently I am hardcoding the height when hovered to be 300, how do I do it such that it gets the height based on the number of tag it has, so say there are 6 and each li is 50px height so then the height is 300.
I am talking about this line specifically:
$(this).stop().animate({"height":"300px"},1000).addClass("dropped");
Also how do I make it such that when it's already expanded, and I click on it again it animates back un-expanded
Get the height of the ul and then set the #expandable animating height.
$("#expandable").click(function() {
var ulHeight = $(this).children("ul").height() + 50;
$(this).stop().animate({"height":ulHeight + "px"},1000).addClass("dropped");
});
DEMO
try this code
$("#expandable").hover(function() {
var _aH = (parseInt($(this).find('ul li').length)+1)*50
$(this).stop().animate({"height":_aH+"px"},1000).addClass("dropped");
}, function() {
$(this).stop().animate({"height":"50px"},1000).removeClass("dropped");
});
see fiddle
basically, you need to calculate number of lis in your ul and then findout the total height.
Code assumes 50px to be the height of the li, you can make that one also generic, by grabbing the height of the li.
Firstly, you need to close the your ul using </ul> not </nav>
Secondly, to make it dynamic instead of harcode height, you need to calculate the total height of your list. Here is how you do it:
var sum = 50;
$('#expandable').find('li').each(function() {
sum += $(this).height();
});
$("#expandable").click(function() {
$(this).stop().animate({"height": sum},1000).addClass("dropped");
});
Working Demo
You can get the height of the ul like that with jQuery:
$('#expandable').find('ul').height();
...then just add the height of the span and you get the computed height for the animation :)
As for your other problem: Just check for your dropped class and animate it back if it is there:
$("#expandable").click(function() {
var ulHeight = $('#expandable').find('ul').height();
var spanHeight = $('span').height();
var computedHeight = (ulHeight + spanHeight);
if( $(this).hasClass('dropped') ) {
$(this).stop().animate({"height": (spanHeight + "px") },1000).removeClass("dropped");
return false;
}
$(this).stop().animate({"height": (computedHeight + "px") },1000).addClass("dropped");
});
See my Fiddle:
Fiddle

Categories