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 :)
Related
How can a row of inline-blocks be wrapped by a shrinking parent resulting in equal (or almost equal) rows?
So instead of wrapping like this:
wrap like this:
And if there's an uneven number of blocks, like this:
You can use CSS Grid grid-template-columns and #media (if you want to wrap by screen-width) or in JS with docment.getElementById('bottomblocks').style.gridTemplateColumns variable to achieve this. (If I understand correctly)
I wrote here an example with JS:
https://jsfiddle.net/Lhbqdt2z/
You can learn about it where I started with it: Coding Tech Talk
Or just from W3Schools
Moz://a has a good examples here
He is something fun I just wrote... Assuming you want an "enhanced wrap" behavior that wraps by the half of its childs, instead of the normal floating.
It's more an "essay" than a strong best practice answer. ;)
$(window).on("load resize",function(){
$(".container div").css({"clear":"initial"});
var wrapped = false;
var wrappedAt = 0;
var wrappedNtimes =0;
var pos = $(".container div").first().offset();
var n = $(".container div").length;
$(".container div").each(function(index){
if(!wrapped){
if( ($(this).offset().top != pos.top)){
console.log("Wrapped at "+index+" out of "+n);
wrapped = true;
wrappedAt = index;
wrappedNtimes++;
}
pos=$(this).offset();
}
});
if(wrapped){
// Force enhanced wrapping... .oO(lol)
console.log("--"+wrappedAt+"--");
var half = Math.ceil(n/(wrappedNtimes+1));
$(".container div").each(function(){
if( $(this).index() != 0 && ($(this).index())%half == 0){
$(this).css({"clear":"left"}); // zero-based.
}
});
}
});
CodePen demo
Here's a solution that inserts <br> elements at the ends of each row. This code can be placed into a function to run whenever you need to wrap the blocks.
// Make sure that the last row of blocks doesn't have 2 less blocks than all
// the previous rows. Assume that all blocks are equal size.
var blocks = sharing.find('.btn');
//what's the parent width
var parentWidth = blocks.parent().width();
//how many blocks can fit in such a width
var maxNumOfBlocksInOneRow = Math.floor(parentWidth / blocks.outerWidth(true));
//repeatable code
var calcNumOfBlocksInLastRow = function(){
var lastRowFull = blocks.length % maxNumOfBlocksInOneRow ? false : true;
if (lastRowFull) {
return maxNumOfBlocksInOneRow;
} else {
return blocks.length % maxNumOfBlocksInOneRow;
}
}
//do we have more blocks than row's maximum?
if (blocks.length > maxNumOfBlocksInOneRow) {
//how many blocks would the last row have
var numOfBlocksInLastRow = calcNumOfBlocksInLastRow();
//if the last row is missing more than 1 block, try with 1 less block in each row
while (numOfBlocksInLastRow < maxNumOfBlocksInOneRow - 1) {
maxNumOfBlocksInOneRow--;
numOfBlocksInLastRow = calcNumOfBlocksInLastRow();
}
//insert <br> at the end of each row
jQuery('<br>').insertAfter(blocks.filter(':nth-child(' + maxNumOfBlocksInOneRow + 'n)'));
}
I want to check if a div has moved to a certain point. Here is my code that isn't working.
JS:
(function deathCondition() {
if (wordlist.offsetTop >= 500) {
alert('hey');
}
})();
I even tried it just being alone.
if (wordlist.offsetTop >= 500) {
alert('hey');
}
not sure if wordlist contains the id or class of the element, but anyway you need to store the id or class of the element:
var wordlist = document.getElementById('wordlist');
then find out the elements offset:
elOffset = wordlist.offsetTop;
I am trying to make an object that will determine the highest height of a set of elements and make each element match the height of the largest.
In this object, I am trying to pass a selector to a JQuery method which resides inside of my object method. Unfortunately I am not able to get each item this way and my Each statement does not fire but the object returns 0 items.
Below is an example of my object:
var heightBalance = {
containerName: '',
childElements: '',
alert: function() {
var divs = $(this.childElements);
console.log(divs);
$.each(divs, function(index, value) {
console.log('working');
});
}
}
heightBalance.containerName = '#containers';
heightBalance.childElements = 'div';
heightBalance.alert();
#one {
background-color: green;
width: 50px;
height: 200px;
}
div {
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="containers">
<div id="one">d</div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
</div>
You're script is initialized in the head, before the divs are rendered. Move the script to the end of the body, or use jQuery ready function (fiddle):
$(function () {
var heightBalance = {
containerName: '',
childElements: '',
alert: function () {
var divs = $(this.childElements);
console.log(divs);
$.each(divs, function (index, value) {
console.log('working');
});
}
}
heightBalance.containerName = '#containers';
heightBalance.childElements = 'div';
heightBalance.alert();
});
The code in this answer will give you the equal heights you want:
$(function() {
// Get an array of all element heights
var elementHeights = $('.features').map(function() {
return $(this).height();
}).get();
// Math.max takes a variable number of arguments
// `apply` is equivalent to passing each height as an argument
var maxHeight = Math.max.apply(null, elementHeights);
// Set each height to the max height
$('.features').height(maxHeight);
});
As the poster above states, your code is initializing in the head before your elements have loaded. If you looked at the object in the console, you can see that the object was referencing the root of your entire document. For future reference, in fiddle, under "Frameworks and Extensions" switching the second dropdown from "nowrap - in head" to "onload" can achieve the same result as the previous answer.
You're defining 2 variables. I assume the intention is to define a context - heightBalance.containerName
and then search that context for the highest child and modify all children to match that height. heightBalance.childElements.
Your function doesn't make use of heightBalance.containerName. so $(this.childElements) just looks for any div on the page. in the console, you can see that the container is being listed along with the child elements.
You probably want to change it to something more like var divs = $('#containers').find('div') or shortform $('div', '#containers')
alert: function(){
var divs = $('#containers').find('div')
console.log(divs);
$.each(divs, function(index, value){
console.log('working');
});
}
I modified my code a little and got this to work. Thank you for everyone showing me when I need to initialize JQuery to get this functioning.
var heightBalance = {
containerName: '',
childElements: '',
heightArray: [],
calc: function(){
var divs = $(this.containerName + " " + this.childElements);
$.each(divs, function(index, value){
var innHeight = $(value).height(); ;
heightBalance.heightArray.push(innHeight);
});
this.largestHeight(this.heightArray);
},
largestHeight: function(data)
{
var i = data.indexOf(Math.max.apply(Math, data));
$(heightBalance.childElements).height(this.heightArray[i] );
}
}
I'm trying to find a way to change a selector's height to its parent's height via jQuery but haven't found any solution yet, you can clearly see in this page I need to get the height of each #accordion ul li and set it to the .status-green
http://jsbin.com/udajen/8/edit
Thank you!
You can see the work example here: http://jsfiddle.net/mikhailov/yQfFc/
$("#accordion li").each(function(index, value) {
var $value = $(this);
var current = $value.height() - 2;
$value.find(".status-green").height(current);
});
the second option is to iterate through .sentence divs:
$("#accordion .sentence").each(function(index, value) {
var $value = $(this);
var current = $value.height() + 10;
$value.siblings(".status-green").height(current);
});
If you want to make the .status-greens height same as associated .sentence height, you must calculate their padding-top and padding-bottom too. here is the complete code:
http://jsfiddle.net/Javad_Amiry/REPuQ/1/
and the js will be:
$("#accordion .sentence").each(function () {
var current = $(this).height();
var p_top = $(this).css("padding-top");
var p_bot = $(this).css("padding-bottom");
$(this).parent().find(".status-green").css({
height:current,
"padding-top":p_top,
"padding-bottom":p_bot
});
});
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.