jQuery - Set min-height of div - javascript

This is probably really easy for most of you. But I'm in need of a small snippet that looks up the current height of a div (the div has a dynamic height based on the content inside it)
and then set that value in the css class's min-height value.
Basically what this means is that I want this container to have it's min-height to be the exact same value as it's current height. This is probably a quick one :)

If I understand you correctly, you could do the following:
$(".foo").css("min-height", function(){
return $(this).height();
});

just a proof of concept!
// attend for dom ready
$(function() {
// hide .foo before we get it's height
$('.foo').hide();
// get the height, also the one mentioned below is a good one!
var foo_height = $('.foo').height();
// see if the actual height respect our needs! esample 180px
if ( foo_height > 180 ) {
// set the height and show it!
//$('.foo').css('height', foo_height + 'px').show(); OR try
$('.foo').height( foo_height ).show();
} else {
//do something else here
}
});
this should work as expected!

var elt = document.getElementById("<%= this.your_element_id.ClientID %>");
elt.style.minHeight = elt.clientHeight + 'px';

Related

jquery if css height > Xpx do this

Is there any way to trigger a function with jquery once a CSS element reaches a certain height?
I imagine an example would look something like:
function(){
if( $("#bar").css('height') > '20px') {
$("#mydiv").show();
});
HTML:
<b style="display:none" id="mydiv">Hello!</b>
Can't seem to find a way to successfully make it work.
Example: http://jsfiddle.net/5ptkqajv/1/
You can add your check in the click-function, so it gets executed when the height is changing:
$('h1').on("click", function() {
advanceRound();
render();
if($("#fill").height() > 60){
$("#mydiv").show();
}
});
Updated Fiddle
Alternativly you cann add the check in your function renderBar().

How would I change the height of a parent div based on the height of a child div?

http://jsfiddle.net/nWb5j/68/
Hi there! As you can see in the jsfiddle above, I have a parent div that has a position of relative with child divs with position of absolute.
<div class="d1">
<div class="d2">W<br>o<br>r<br>l<br>d
</div>
<div class="d3">Hello</div>
</div>
d1 has a position of relative, while d2 and d3 have positions of absolute.
I have tried the following jQuery to no success:
$('.d1').css(height,($( "d3" ).height());
(As you can probably tell, I have no clue what I'm doing.)
I would like for the parent div to have the height of whatever the tallest child is, if possible. If that doesnt work, then to have the parent the same height as one of the children would work too.
I am very new to jQuery and javascript and have tried a few things, but none of them seem to work.
Thanks in advance!
Possible duplicate of Auto height on parent container with Absolute/Fixed Children
So your answer would be:
The parent div can not use "height:auto" when its children are positioned absolute / fixed.
You would need to use JavaScript to achieve this.
In jquery something like.
var biggestHeight = "0";
// Loop through elements children to find & set the biggest height
$("#d1 *").each(function(){
// If this elements height is bigger than the biggestHeight
if ($(this).height() > biggestHeight ) {
// Set the biggestHeight to this Height
biggestHeight = $(this).height();
}
});
// Set the container height
$("#d1").height(biggestHeight);
Working example
http://jsfiddle.net/blowsie/dPCky/1/
Customized example for you
http://jsfiddle.net/nWb5j/68/
Just use Math.max here is the demo
var d2Height = $("#d2").height(),
d3Height = $("#d3").height(),
largest = Math.max(d2Height, d3Height);
$('#d1').css({"height":largest});
In your case these two lines of javascript resolves the problem:
var height = Math.max($( "#d2" ).height(),$( "#d3" ).height());
$('#d1').height(height);
See updated fiddle:
http://jsfiddle.net/nWb5j/69/
You can try this...
var maxHeight =0;
//get the max height of child div
$(".d1 > div").height(function(i, h){
if (h > maxHeight ) {
maxHeight = h;
}
});
$(".d1").height(maxHeight);

jquery keeps on selecting element after changing the class

I have a button which must change what it does after meeting some condition.
So I'm selecting the button by it's class and I want to remove that class upon meeting the condition and add a new class to the element and do something else with it. but it's not working.
I just made up an example for my problem.
this is the code:
$('.button-1').click(function(){
$('.box').width(function(){
return $(this).width() + 10;
});
$(this).removeClass('button-1').addClass('button-2');
});
$('.button-2').click(function(){
$('.box').width(function(){
return $(this).width() - 10;
});
$(this).removeClass('button-2').addClass('button-1');
});
and it's Fiddle
I expect this to toggle between increasing and decreasing the black box width, but it keeps on increasing.
That's because the event is bound statically on the button, use event delegation like this:
$(document).on('click','.button-1', function(){
$('.box').width(function(){
return $(this).width() + 10;
});
$(this).removeClass('button-1').addClass('button-2');
});
$(document).on('click','.button-2', function(){
$('.box').width(function(){
return $(this).width() - 10;
});
$(this).removeClass('button-2').addClass('button-1');
});
DEMO
Offcourse you could do it like that...but isn't it easier to add an another variable that checks whether or not there has been a click? The code is much simpler and you can check later on whether or not the box has been enlarged.
This method also seperates style from computing, which is generally regarded as a good idea.
var large = false;
$('body').on('click', '.button', function(){
if (large) {
$('.box').addClass('clicked');
large = false;
} else {
$('.box').removeClass('clicked');
large = true;
}
});
additionally, you need a css class like so:
.clicked {
width: 110px;
}
and I removed that button-1 and button-2 classes, gave the div the class 'button' instead

The size (width) of text in different browsers

I need to fit text in div box with exact width.
Is there a way (for example with javascript) to make the text look the same size in all major browsers?
For example strip some letters if text does not fit 'div' box.
Just add the following properties to the CSS rule for your div:
overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
You can see this in action here (JSFiddle).
First of, set your font face and size with css. Then you will almost always have the same width.
Then you can add overflow: hidden; to your div so it won't show anything that goes past the end.
Depending on how you're doing this, you could use padding and margins without setting a width, that way it will always fit in the div. Although this may not be what you want.
You can truncate your text with CSS or with JavaScript. Here's an example of a simple JQuery truncation plugin I wrote which allows for a "show more" link if the text is truncated:
$.fn.trunc = function(_break_at) {
var _article = jQuery(this).text();
var _leader = [];
var _trailer = [];
var _substr = _article.split(' ');
$(this).wrapInner('<div class="long"></div>');
$.each(_substr, function(i, data) {
if (i < _break_at) {
_leader.push(data);
}
});
if (_substr.length > _break_at) {
$('<div/>').addClass('short').html(_leader.join(' ')).prependTo(this);
$('<span/>').appendTo('.long').addClass('toggle').html(' << Show less');
$('<span/>').appendTo('.short').addClass('toggle').html('... Show more >>');
}
$('.toggle').click(function() {
$('.short, .long').toggle('show');
});
};
$(function() {
// This is how you use it
$('#article_body').trunc(2);
});
http://jsfiddle.net/AlienWebguy/7ZamJ

Need to find height of hidden div on page (set to display:none)

I need to measure the offsetHeight of a div that is inside of a hidden element.
<div id="parent" style="display: none;">
<div id="child">Lorem Ipsum dolor sit amet.</div>
</div>
The parent div must be set to "display:none". I have no control over that. I realize that the offsetHeight of the child div is going to be 0. I need to find a workaround.
Something I've toyed with is when the page loads, I copy the childnodes of parent, inject in a div on the page that is set to "visiblity:hidden". Then I measure the height of those elements, and remove the nodes when done.
Any other thoughts?
Update:
What I wound up having to do was this:
Using YUI 2, on page load, I found all elements of that given classname that were either set to display:none, or whose height and width was 0 (that's one way of measuring whether an element exists, or a parent is set to display:none). I then set that element to display:block. I then checked it's parent for the same thing and showed the parents until it finds a visible parent. Once highest display:none ancestor is set to display:block, I can measure my element.
Once all elements are measured I reset all of the elements back to display:none.
You need to make element's parent visible for that one very short moment while you're getting element's dimensions. In a generic solution, all ancestors are usually traversed and are made visible. Then their display values are set back to original ones.
There are performance concerns of course.
We considered this approach in Prototype.js implementation but ended up with getWidth and getHeight making only actual element visible, without traversing ancestors.
The problem with alternative solutions - such as taking element out of "hidden" parent - is that certain styles might no longer apply to an element once it's out of its "regular" hierarchy. If you have a structure like this:
<div class="foo" style="display:none;">
<div class="bar">...</div>
</div>
and these rules:
.bar { width: 10em; }
.foo .bar { width: 15em; }
then taking element out of its parent will actually result in wrong dimensions.
If you use style.display = "none", the element will have 0 width and height,
but using the style.visibility = "hidden" instead, the element will have the width and height calculated by the browser (as normally).
A workaround is to set the height to 0
.hidden {
height: 0;
overflow: hidden;
}
Then to get the elements scrollHeight.
document.querySelector('.hidden').scrollHeight
The scrollHeight will correctly give you the height though the element does not appear. I don't think it affects element flow either.
Example: https://jsfiddle.net/de3vk8p4/7/
Reference: https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements#How_big_is_the_content.3F
You could clone the element, absolutely position it at -10000,-10000, measure the clone and destroy it.
Made a pure js solution with no Jquery and with no cloning (which I guess is faster)
var getHeight = function(el) {
var el_style = window.getComputedStyle(el),
el_display = el_style.display,
el_position = el_style.position,
el_visibility = el_style.visibility,
el_max_height = el_style.maxHeight.replace('px', '').replace('%', ''),
wanted_height = 0;
// if its not hidden we just return normal height
if(el_display !== 'none' && el_max_height !== '0') {
return el.offsetHeight;
}
// the element is hidden so:
// making the el block so we can meassure its height but still be hidden
el.style.position = 'absolute';
el.style.visibility = 'hidden';
el.style.display = 'block';
wanted_height = el.offsetHeight;
// reverting to the original values
el.style.display = el_display;
el.style.position = el_position;
el.style.visibility = el_visibility;
return wanted_height;
}
here is the demo
https://jsfiddle.net/xuumzf9k/1/
Please let me know if you can find any improvements to this (as I use this in my main projects)
So here's working jQuery solution based on lod3n's answer and with help of 999's comment:
var getHiddenElementHeight = function(element){
var tempId = 'tmp-'+Math.floor(Math.random()*99999);//generating unique id just in case
$(element).clone()
.css('position','absolute')
.css('height','auto').css('width','1000px')
//inject right into parent element so all the css applies (yes, i know, except the :first-child and other pseudo stuff..
.appendTo($(element).parent())
.css('left','-10000em')
.addClass(tempId).show()
h = $('.'+tempId).height()
$('.'+tempId).remove()
return h;
}
Enjoy!
A helper function ---
function getElementHeight(el) {
var clone = el.cloneNode(true);
var width = el.getBoundingClientRect().width;
clone.style.cssText = 'position: fixed; top: 0; left: 0; overflow: auto; visibility: hidden; pointer-events: none; height: unset; max-height: unset; width: ' + width + 'px';
document.body.append(clone);
var height = clone.getBoundingClientRect().height + 'px';
clone.remove();
return height;
}
Creates a clone, appends it to the DOM (hidden), takes the height, then removes it.
Position of fixed and the top/left are in case your app allows scrolling at the body-level - it attempts to prevent a scrollbar rave party - can remove if you handle scrolling in children elements.
Overflow, height, and max-height settings to attempt to 'reset' height settings and let it be it's natural height on the clone.
Visibility for the obvious and pointer-events as a 'just in case' the rendering of the element takes a while and don't want to interrupt user-input.
An example having an 'accordion-like' animated open/close allowing for dynamic heights.
function getElementHeight(el) {
var clone = el.cloneNode(true);
clone.style.cssText = 'position: fixed; top: 0; left: 0; overflow: auto; visibility: hidden; pointer-events: none; height: unset; max-height: unset';
document.body.append(clone);
var height = clone.getBoundingClientRect().height + 'px';
clone.remove();
return height;
}
var expanded = false;
var timeout;
function toggle() {
var el = document.getElementById('example');
expanded = !expanded;
if (expanded) {
el.style.maxHeight = getElementHeight(el);
// Remove max-height setting to allow dynamic height after it's shown
clearTimeout(timeout);
var openTimeout = timeout = setTimeout(function() {
el.style.maxHeight = 'unset';
clearTimeout(openTimeout);
}, 1000); // Match transition
} else {
// Set max height to current height for something to animate from
el.style.maxHeight = getElementHeight(el);
// Let DOM element update max-height, then set to 0 for animated close
clearTimeout(timeout);
var closeTimeout = timeout = setTimeout(function() {
el.style.maxHeight = 0;
clearTimeout(closeTimeout);
}, 1);
}
}
#example {
overflow: hidden;
max-height: 0;
transition: max-height 1s;
}
<button onclick="toggle()">Toggle</button>
<div id="example">
<textarea>Resize me</textarea>
</div>
In the JS please use 'scrollHeight'
Example Code
Assume that this div is hidden in DOM
<div class="test-div">
//Some contents
<div>
Javascript to find this div height
const testHeight = document.querySelector('.test-div');
testHeight.scrollHeight
Use z-index to hide element under non-transparent element, show it, and get height.
Until the element is rendered, it has no height. Even if you clone the parent object and display it somewhere that can't be seen by the user, there's not guarantee that the clone will have the same height as the final size of the hidden object.
There are many things that can affect the height that wouldn't necessarily be rendered in the clone - anything in the DOM and its interaction with the CSS rules could cause a change in rendering any other element of the DOM. Short of cloning the entire document (and even that's not fool-proof) you have no way of determining the height of the hidden object.
If you must know the height before it's displayed to the user, you'll have to "hack" it by displaying it for as short of a time as possible then hiding it again. Most likely, the user will see this hiccup and not be pleased by the result.
So, you cannot even change the display:none; to height:0; overflow:hidden; ? Maybe you could override that in your own stylesheet like so:
div#parent { display: block !important; height:0; overflow:hidden; }
And then as you are using YUI (assuming YUI 2) you could use this:
var region = YAHOO.util.Dom.getRegion('child');
To get the dimensions and offset of the child.
Try to use:
#parent{ display:block !important; visibility:hidden; position:absolute}
What I wound up having to do was this:
Using YUI 2, on page load, I found all elements of that given classname that were either set to display:none, or whose height and width was 0 (that's one way of measuring whether an element exists, or a parent is set to display:none). I then set that element to display:block. I then checked it's parent for the same thing and showed the parents until it finds a visible parent. Once highest display:none ancestor is set to display:block, I can measure my element.
Once all elements are measured I reset all of the elements back to display:none.
Did you try this ?
setTimeout('alert($(".Var").height());',200);

Categories