Kamis, 02 Februari 2012

How to Push Parent Element to the Height of Absolute Positioned DIV

I have found something in a forum. Someone wants something like a tooltip that will appear on the right side from a list, but he wanted the parent element to follow the height of the highest tooltip when it appears. The problem is, tooltip uses an absolute positioning, while the absolute position is very difficult to give impact to the parent element because the word "absolute" in CSS is similar to "move away from the flow and the container".

The Problem

When you have added the tooltip on any list with different heights, you have found something that is annoying when you see to the lowest list or when you know that tootip with the highest height looks overflowing of the area should be:

That You Want

What you want is when the tooltip position/height has exceeded the area, you want it's parent element to follow the tooltip height as well as the area behavior in general. But because here we use absolute position for the tooltip, we can't do that purely with CSS, we need something WOW such as JQuery. Then... OK. We need a little help from JQuery:

The JQuery

This code will change the height of parent element if the tooltip in it has exceeded the highest limit of it's parent, and also calculate the offset of the tooltip. So, if the tooltip has a top value that is not explicitly calculated, this code will continue to customize it. At least that's what I got so far:
$(function() {
// When the li element hovered...
$('ul.tooltip li').hover(function() {
// Show the tooltip
$('div.child', this).show();
// Then...
var offset = $('div.child', this).offset().top - $(this).parent().offset().top,
maxHeight = $('div.child', this).outerHeight() + offset;
// If it's parent height smaller than "maxHeight" ...
if($(this).parent().height() < maxHeight) {
// Set the parent height to "maxHeight"
$(this).parent().css('height', maxHeight);
} else {
// If not, set the parent height to auto
$(this).parent().css('height', 'auto');
}

}, function() {
// Hide the tooltip and set the height to auto for it's parent element.
$(this).parent().css('height', 'auto');
$('div.child', this).hide();

});

});
<!-- SAMPLE MARKUP -->
<div id="outer">
<ul class="tooltip">
<li><h4>Lorem Ipsum</h4>
Lorem ipsum dolor sit amet...
<div class="child"> content here... </div>
</li>
<li><h4>Lorem Ipsum</h4>
Lorem ipsum dolor sit amet...
<div class="child"> content here... </div>
</li>
<li><h4>Lorem Ipsum</h4>
Lorem ipsum dolor sit amet...
<div class="child"> content here... </div>
</li>
<li><h4>Lorem Ipsum</h4>
Lorem ipsum dolor sit amet...
<div class="child"> content here... </div>
</li>
</ul>
</div>

And also, remove this code from the CSS:
ul.tooltip li:hover .child {
display:block;
}

0 komentar:

Posting Komentar