jQuery addClass only to div with class which is really higher - javascript

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');
}
});

Related

Set element height equal to width using Vanilla javascript

I have a Nodelist of 10 elements which I am getting using below:
let elements = document.getElementById('all-photos-root').querySelectorAll('.photo-root');
This gives me a NodeList with 10 elements. The initial width on each element is set in percentage which is 25%. I want to set the height of each element equal to the width in pixels so that it always renders as a square.
I am doing it like below, but I always get width is undefined.
for (var i = 0; i < elements.length; i++) {
console.log('elements', elements[i], elements[i].style.width);
elements[i].style.height = elements[i].style.width;
}
Using Element#style will only get the properties that have been set inline (the properties in the style attribute, properties on the css won't be included).
If you want to get the currently active property you should use getComputedStyle.
You can also use offsetWidth, clientWidth or scrollWidth to get the width of the block in pixels (in number format).
var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var fooBar = document.getElementById("foo-bar");
console.log("Foo:");
console.log(foo.style.width); // 30px
console.log(getComputedStyle(foo).width); // 30px
console.log(foo.offsetWidth);
console.log("Bar:");
console.log(bar.style.width); // hasn't been defined using style attribue
console.log(getComputedStyle(bar).width); // 40px as defined in #bar css block
console.log(bar.offsetWidth);
console.log("FooBar:");
console.log(fooBar.style.width); // hasn't been defined using style attribute
console.log(getComputedStyle(fooBar).width); // will actually give the absolute width in `px` instead of the `50%` used in css block
console.log(fooBar.offsetWidth);
#bar {
width: 40px;
}
#foo-bar {
width: 50%;
}
<div id="foo" style="width: 30px;"></div>
<div id="bar"></div>
<div id="foo-bar"></div>
for (var i = 0; i < elements.length; i++) {
// width and height in pixels, including padding and border
// Corresponds to jQuery outerWidth()
let width = elements[i].offsetWidth;
// width and height in pixels, including padding, but without border
// Corresponds to jQuery innerWidth()
width = elements[i].clientWidth;
// Need to add the px at the end
elements[i].style.height = width + 'px';
}

jQuery Find height of the largest element

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

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/

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

How to find the width of a div using vanilla JavaScript?

How do you find the current width of a <div> in a cross-browser compatible way without using a library like jQuery?
document.getElementById("mydiv").offsetWidth
element.offsetWidth (MDC)
You can use clientWidth or offsetWidth Mozilla developer network reference
It would be like:
document.getElementById("yourDiv").clientWidth; // returns number, like 728
or with borders width :
document.getElementById("yourDiv").offsetWidth; // 728 + borders width
All Answers are right, but i still want to give some other alternatives that may work.
If you are looking for the assigned width (ignoring padding, margin and so on) you could use.
getComputedStyle(element).width; //returns value in px like "727.7px"
getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log(rect.width);
}
You can also search the DOM using ClassName. For example:
document.getElementsByClassName("myDiv")
This will return an array. If there is one particular property you are interested in. For example:
var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;
divWidth will now be equal to the the width of the first element in your div array.
Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:
var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.
call below method on div or body tag onclick="show(event);"
function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.
function getStyleInfo() {
setTimeout(function() {
const style = window.getComputedStyle(document.getElementById('__root__'));
if (style.height == 'auto') {
getStyleInfo();
}
// IF we got here we can do actual business logic staff
console.log(style.height, style.width);
}, 100);
};
window.onload=function() { getStyleInfo(); };
If you use just
window.onload=function() {
var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}
you can get auto values for width and height because browsers does not render till full load is performed.

Categories