Reputation: 64
I currently have a parent element that has children whom are positioned absolute. This destroys the height of the parent element, essentially, and I would like to add back the height based on the child that is currently being displayed (all children have different heights).
<button id="one">One</button>
<button id="two">Two</button>
<button id="three">Three</button>
<div id="parent">
<div class="child">height of 250px</div>
<div class="child">height of 500px</div>
<div class="child">height of 750px</div>
</div>
I have JQuery in place to show one of the children and add a class of, 'active' when you press one of the buttons. For instance: When you press button#one the first child shows and is given the class of, 'active'. The current JQuery that I have for height is:
var maxHeight = 0;
$('.child').each(function() {
if($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$('#parent').height(maxHeight);
This only grabs and applies the tallest child's height (750px), when I would like the height to be dynamic based on what child is being shown and/or has the class of 'active'.
Upvotes: 1
Views: 72
Reputation: 682
From your description it's hard to understand your problem. I tried to guess it and create a snippet. I hope it helps!
var parent = $('#parent');
$('[data-target]').each(function() {
$(this).bind('click', function(){
var elID = $(this).data('target');
var elHeight = $('#'+elID).height();
parent.height(elHeight);
console.log(elID, elHeight)
})
});
#parent {
border: 3px solid red;
}
.child {
position: absolute;
width: 200px;
}
.child:nth-child(1) {height: 20px; background-color: steelblue;}
.child:nth-child(2) {height: 40px; background-color: wheat;}
.child:nth-child(3) {height: 60px; background-color: firebrick;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-target="one" >One</button>
<button data-target="two" >Two</button>
<button data-target="three" >Three</button>
<div id="parent">
<div class="child" id="one">height of 20px</div>
<div class="child" id="two">height of 40px</div>
<div class="child" id="three">height of 60px</div>
</div>
Upvotes: 1