Get values from one .each function into a different .each function - javascript

I have 4 sub-banners with display: block; width: 100%; that each have a div with text inside. These divs hangs down outside the parent element using transform: translateY(238px).
Each div that holds the text is of varying height so I was trying to write a function to check each text div's height and apply the margin to the bottom of that specific parent element accordingly.
What I got so far is this, but I can't figure out how to get the variable respectiveMargin passed into my second each function so that it matches up with the right parent element. Right now it just applies the same margin on all sub-banners. Thanks for any and all help!
const resize = () => {
if ($(window).width() < 768) {
$('.sub-banner-text-wrapper').each(function () {
var textHeight = $(this).height();
var responiveMargin = (textHeight - 62) + 25;
});
$('.sub-banner').each(function () {
$(this).css("margin-bottom", responiveMargin);
});
}
};
$(window).on('resize', resize);

Seems the main problem is that you're trying to use two .eaches when you only need one:
const resize = () => {
if ($(window).width() < 768) {
$('.sub-banner-text-wrapper').each(function () {
var textHeight = $(this).height();
var responiveMargin = (textHeight - 62) + 25;
$(this).closest('.sub-banner').css("margin-bottom", responiveMargin);
});
}
};
$(window).on('resize', resize);

So reference the index when you loop over the one set.
var banners = $('.sub-banner');
$('.sub-banner-text-wrapper').each(function (ind) {
var textHeight = $(this).height();
var responiveMargin = (textHeight - 62) + 25;
banners.eq(ind).css("margin-bottom", responiveMargin);
});
If it happens to be a child/parent element, than you can just select it.
var banners = $('.sub-banner');
$('.sub-banner-text-wrapper').each(function (ind) {
var textHeight = $(this).height();
var responiveMargin = (textHeight - 62) + 25;
//If a child
$(this).find(".sub-banner").css("margin-bottom", responiveMargin);
//or a parent
$(this).parent().css("margin-bottom", responiveMargin);
});

Maybe Something like this?
if ($(window).width() < 768) {
$('.sub-banner-text-wrapper').each(function () {
var subBanner = $(this).closest('.sub-banner').attr('class');
var textHeight = $(this).height();
var responiveMargin = (textHeight - 62) + 25;
$(subBanner).css("margin-bottom", responiveMargin);
});
}

Related

Function inside resize function is not working

i have this piece of code.
First i'm setting some heights - the code works on load and on resize.
However, setting heights based on the highest item it doesn't work on resize, but only on load. Can you give me an advice?
$(window).resize(function () {
// speakers - height equal to width
var imgwidth = $('.speakers-section-items-item-image').width();
$('.speakers-section-items-item-image').css({'height': imgwidth + 'px'});
var height = $('.executive-section-items-item-img').height();
$('.executive-section-items-item-list').css({'line-height': height + 'px'});
var heightTeam = $('.team-section-items-item-img').height();
$('.team-section-items-item-meta-last').css({'line-height': heightTeam + 'px'});
// set heights based on the highest item
var maxHeightTeam = -1;
$('.team-section-items-item').each(function () {
maxHeightTeam = maxHeightTeam > $(this).height() ? maxHeightTeam : $(this).height();
});
$('.team-section-items-item').each(function () {
$(this).height(maxHeightTeam);
});
var maxHeightExecutive = -1;
$('.executive-section-items-item').each(function () {
maxHeightExecutive = maxHeightExecutive > $(this).height() ? maxHeightExecutive : $(this).height();
});
$('.executive-section-items-item').each(function () {
$(this).height(maxHeightExecutive);
});
var maxHeightSpeakers = -1;
$('.speakers-section-items-item').each(function () {
maxHeightSpeakers = maxHeightSpeakers > $(this).height() ? maxHeightSpeakers : $(this).height();
});
$('.speakers-section-items-item').each(function () {
$(this).height(maxHeightSpeakers);
});
}).resize();

jQuery resize function with css height

I'm trying to set a height to a div that it's parent have. I've tried and when I use console.log() it's actually working. But the height doesn't set without a refresh.....
This is my function
// Set Hight
function fixingHeight() {
function setHeight() {
var windowWidth = window.innerWidth;
var latestPostsWrapperHeight = $('#latestPosts').height();
var tabPane = $('#latestPosts').find('.tab-pane');
var tabPaneLists = $('#latestPosts').find('.tab-pane').find('li a');
var popularPostsWrapperHeight = $('#popularPosts').height();
var profileWrapper = $('#popularPosts').find('.pofile-wrapper');
if(windowWidth > 767) {
$.each(tabPane, function() {
$(this).height(latestPostsWrapperHeight - 70);
});
$.each(tabPaneLists, function() {
$(this).height((latestPostsWrapperHeight - 70) / 5 - 1);
});
$.each(profileWrapper, function() {
$(this).outerHeight(popularPostsWrapperHeight);
});
}
//console.log(windowWidth);
}setHeight();
$(window).resize(function() {
setHeight();
});
}fixingHeight();
To handle window resize event, call the function $(window).resize outside of the function setHeight()
to call setHeight() on first load, use the jquery handler $(document).ready
This is the final code :
function setHeight() {
var windowWidth = window.innerWidth;
var latestPostsWrapperHeight = $('#latestPosts').height();
var tabPane = $('#latestPosts').find('.tab-pane');
var tabPaneLists = $('#latestPosts').find('.tab-pane').find('li a');
var popularPostsWrapperHeight = $('#popularPosts').height();
var profileWrapper = $('#popularPosts').find('.pofile-wrapper');
if(windowWidth > 767) {
$.each(tabPane, function() {
$(this).height(latestPostsWrapperHeight - 70);
});
$.each(tabPaneLists, function() {
$(this).height((latestPostsWrapperHeight - 70) / 5 - 1);
});
$.each(profileWrapper, function() {
$(this).outerHeight(popularPostsWrapperHeight);
});
}
console.log(windowWidth);
}
$(document).ready(function() {
setHeight();
});
$(window).resize(function() {
setHeight();
});
remove the function wrapper fixingHeight(), 'setHeight()' is enough
$(window).resize dont't run because it is in a function so this is not working without calling the function wrapper, so get it outside of the function.
as # joram say, you can call $(document).ready when your document finish loading, so is ready.
$(document).ready(function() {
setHeight();
});
$(window).resize(function() {
setHeight();
});
function setHeight() {
var windowWidth = window.innerWidth;
console.log(windowWidth);
var latestPostsWrapperHeight = $('#latestPosts').height();
var tabPane = $('#latestPosts').find('.tab-pane');
var tabPaneLists = $('#latestPosts').find('.tab-pane').find('li a');
var popularPostsWrapperHeight = $('#popularPosts').height();
var profileWrapper = $('#popularPosts').find('.pofile-wrapper');
if(windowWidth > 767) {
$.each(tabPane, function() {
$(this).height(latestPostsWrapperHeight - 70);
});
$.each(tabPaneLists, function() {
$(this).height((latestPostsWrapperHeight - 70) / 5 - 1);
});
$.each(profileWrapper, function() {
$(this).outerHeight(popularPostsWrapperHeight);
});
}
}

Jquery ui draggable - auto resize parent containment [duplicate]

This question already has answers here:
JqueryUI Draggable - Auto resize parent container
(2 answers)
Closed 7 years ago.
I am sorry my English is not that great. I would like my container element to resize to always contain its child elements.
Visit jsfiddle.net/datakolay/LakYy/
$(document).ready(function() {
var
$document = $(document),
$parent = $("#parent"),
$container = $(".container", $parent),
offset = $container.offset(),
scrollbarSafety = 15;
$container.height($document.height() - offset.top - scrollbarSafety);
$("#eleman,#eleman2")
.draggable(
{
containment: $container,
drag:
function(event, ui)
{
var
$draggee = $(this),
draggeePosition = $draggee.position(),
shouldHeight = draggeePosition.top + $draggee.height() + 15;
if($parent.height() < shouldHeight)
{
$parent.height(shouldHeight);
}
if($parent.height() > shouldHeight)
{
$parent.height(shouldHeight);
}
}
}
);
});
You can use the following to figure out the shouldHeight - essentially:
use a selector to get all the draggables
Get its height and compare it to what you currently have
Set the height.
Here's the meat of the how to:
var shouldHeight = 0;
$(".ui-draggable").each(function () {
var draggeePosition = $(this).position();
if (shouldHeight < draggeePosition.top + $(this).height() + 15) {
shouldHeight = draggeePosition.top + $(this).height() + 15;
}
});
fiddle: http://jsfiddle.net/LakYy/3/
http://jsfiddle.net/LakYy/5/
$(document).ready(function() {
var
$document = $(document),
$parent = $("#parent"),
$container = $(".container", $parent),
offset = $container.offset(),
scrollbarSafety = 15;
$container.height($document.height() - offset.top - scrollbarSafety);
$("#eleman,#eleman2")
.draggable(
{
containment: $container,
drag:
function(event, ui)
{
var shouldHeight = getdraggablemaxheight();
if($parent.height() < shouldHeight)
{
$parent.height(shouldHeight);
}
if($parent.height() > shouldHeight)
{
$parent.height(shouldHeight);
}
}
}
);
});
function getdraggablemaxheight() {
var $parent = $("#parent"),
$container = $(".container", $parent),
maxheight = 0,
currentheight = 0,
currentposition;
$container.children().each(function(index, element) {
currentposition = $(element).position();
currentheight = currentposition.top + + $(element).height() + 15;
if(currentheight > maxheight)
maxheight = currentheight;
});
return maxheight;
Based on the solution by #caspian you may find this variation scales better with many draggables. Same thing really, but only finds the dom positions once per item:
$(".ui-draggable").each(function () {
var draggeeHeight = $(this).position().top + $(this).height() + 15;
if (shouldHeight < draggeeHeight) {
shouldHeight = draggeeHeight;
};
});
if ($parent.height() != shouldHeight) {
$parent.height(shouldHeight);
}
I needed this as well for a project, here is the fiddle
http://jsfiddle.net/genkilabs/WCw8E/2/
To #coding_idiot, what you are asking about will w the default behavior if you use overflow-x: scroll;

jQuery Set Height of Element to Highest in the group

I'm trying to work with jQuery to find the highest element from the first 3 elements within a div then set all 3 the same height then check the next 3 and set them.. etc.. if my window width == X, also if the window width is < X then find the highest 2 elements then set them, then the next 2 then the next 2 etc.
This is my current code which works for all the elements, I would just like to to go through the elements in groups (2's and 3's) and set the height for that group based on the result and window size.
// Find highest element and set all the elements to this height.
$(document).ready(function () {
// Set options
var height = 0;
var element_search = "#cat_product_list #cat_list";
var element_set = "#cat_product_list #cat_list";
// Search through the elements set and see which is the highest.
$(element_search).each(function () {
if (height < $(this).height()) height = $(this).height();
//debug_(height,1);
});
// Set the height for the element(s if more than one).
$(element_set).each(function () {
$(element_set).css("height", (height+40) + "px");
});
});
Any help is much appreciated :)
Try this for setting all of them to the max height:
$(document).ready(function() {
var maxHeight = 0;
$("#cat_product_list #cat_list").each(function() {
if ($(this).outerHeight() > maxHeight) {
maxHeight = $(this).outerHeight();
}
}).height(maxHeight);
});
Update 22/09/16: You can also achieve the same thing without any Javascript, using CSS Flexbox. Setting the container element to have display: flex will automatically set the heights of the elements to be the same (following the highest one).
I've sorted this now,
Check out my Fiddle:
http://jsfiddle.net/rhope/zCdnV/
// Find highest element and set all the elements to this height.
$(document).ready(function () {
// If you windows width is less than this then do the following
var windowWidth = $(window).width();
if (windowWidth < 2000) {
var i = 0,
quotes = $("div#cat_product_list").children(),
group;
while ((group = quotes.slice(i, i += 2)).length) {
group.wrapAll('<div class="productWrap"></div>');
}
}
// Find the width of the window
var windowwidth = $(window).width();
//debug_(windowwidth);
// Set options
var height = 0;
var element_wrap = ".productWrap";
var element_search = ".cat_list";
// Search through the elements set and see which is the highest.
$(element_wrap).each(function () {
$(this).find(element_search).each(function () {
if (height < $(this).height()) height = $(this).height();
});
//alert("Block Height: " +height);
// Set the height for the element wrap.
$(this).css("height", (height) + "px");
// Unset height
height = 0;
});
});
Just to add another suggestion. Here is a jQuery plugin I wrote that accepts one parameter. You can call it like this:
$('.elementsToMatch').matchDimensions("height");
You can match the height, width or if no parameter is entered, both dimensions.
$(function() {
$(".matchMyHeight").matchDimensions("height");
});
(function($) {
$.fn.matchDimensions = function(dimension) {
var itemsToMatch = $(this),
maxHeight = 0,
maxWidth = 0;
if (itemsToMatch.length > 0) {
switch (dimension) {
case "height":
itemsToMatch.css("height", "auto").each(function() {
maxHeight = Math.max(maxHeight, $(this).height());
}).height(maxHeight);
break;
case "width":
itemsToMatch.css("width", "auto").each(function() {
maxWidth = Math.max(maxWidth, $(this).width());
}).width(maxWidth);
break;
default:
itemsToMatch.each(function() {
var thisItem = $(this);
maxHeight = Math.max(maxHeight, thisItem.height());
maxWidth = Math.max(maxWidth, thisItem.width());
});
itemsToMatch
.css({
"width": "auto",
"height": "auto"
})
.height(maxHeight)
.width(maxWidth);
break;
}
}
return itemsToMatch;
};
})(jQuery);
.matchMyHeight {background: #eee; float: left; width: 30%; margin-left: 1%; padding: 1%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="matchMyHeight">
Div 1
</div>
<div class="matchMyHeight">
Div 2
</div>
<div class="matchMyHeight">
Div 6<br> Div 6<br> Div 6<br> Div 6
</div>
var highHeight = "0";
$(".item").each(function(){
var thHeight = $(this).height();
if(highHeight < thHeight ){
highHeight = thHeight;
}
});
console.log(highHeight)

javascript toggle animation issue

I am doing a small javascript animation. this is my code :
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
heading.onclick = function () {
var divHeight = 250;
var speed = 10;
var myInterval = 0;
alert(divHeight);
slide();
function slide() {
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
alert('i am called as slide down')
}
}
function slideUp() {
var anima = document.getElementById('anima');
if (divHeight <= 0) {
divHeight = 0;
anima.style.height = '0px';
clearInterval(myInterval);
} else {
divHeight -= speed;
if (divHeight < 0) divHeight = 0;
anima.style.height = divHeight + 'px';
}
}
function slideDwn() {
var anima = document.getElementById('anima');
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
} else {
divHeight += speed;
anima.style.height = divHeight + 'px';
}
}
}
}
i am using above code for simple animation. i need to get the result 250 on the first click, as well second click i has to get 0 value. but it showing the 250 with unchanged. but i am assigning the value to set '0', once the div height reached to '0'.
what is the issue with my code? any one help me?
Everytime you click on the div the divHeight variable is reset to 250, thus your code never calls slideDwn. Moving the divHeight declaration outside the event handler should do the trick.
Also, your div wont have the correct size when any of the 2 animations end. You're setting the divHeight variable to 250 or 0 correctly, but never actually setting anima.style.height after that.
I've rewritten your code into something simpler and lighter. The main difference here is that we're using a single slide() function here, and that the height of the div in question is stored in a variable beforehand to ensure that the element slides into the correct position.
Note that this is a very simplistic implementation and assumes that the div carries no padding. (The code uses ele.clientHeight and ele.style.height interchangeably, which admittedly, is a pretty bad choice, but is done here to keep the code simple)
var heading = document.getElementsByTagName('h1')[0],
anima = document.getElementById('anima'),
divHeight = anima.clientHeight,
speed = 10,
myInterval = 0,
animating = false;
function slide(speed, goal) {
if(Math.abs(anima.clientHeight - goal) <= speed){
anima.style.height = goal + 'px';
animating = false;
clearInterval(myInterval);
} else if(anima.clientHeight - goal > 0){
anima.style.height = (anima.clientHeight - speed) + 'px';
} else {
anima.style.height = (anima.clientHeight + speed) + 'px';
}
}
heading.onclick = function() {
if(!animating) {
animating = true;
var goal = (anima.clientHeight >= divHeight) ? 0 : divHeight;
myInterval = setInterval(slide, 13, speed, goal);
}
}
See http://www.jsfiddle.net/yijiang/dWJgG/2/ for a simple demo.
I've corrected your code a bit (See working demo)
window.onload = function () {
var heading = document.getElementsByTagName('h1')[0];
var anima = document.getElementById('anima');
var divHeight = 250;
heading.onclick = function () {
var speed = 10;
var myInterval = 0;
function slideUp() {
divHeight -= speed;
if (divHeight <= 0) {
divHeight = 0;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slideDwn() {
divHeight += speed;
if (divHeight >= 250) {
divHeight = 250;
clearInterval(myInterval);
}
anima.style.height = divHeight + 'px';
}
function slide() {
console.log(divHeight )
if (divHeight == 250) {
myInterval = setInterval(slideUp, 30);
} else {
myInterval = setInterval(slideDwn, 30);
}
}
slide();
}
}​

Categories