Set height of a div dynamically - javascript

I try to adjust the height of a div, based on the height of another div. Looks quite simple.. But unfortunately, it does not work. So please give me a hand in this. Here is my code:
anderblokhoogte = document.getElementById('slider-gaea');
var curblok = document.getElementById('curiculum');
curblok.clientHeight = anderblokhoogte.clientHeight + 'px !important';
I proved the element 'slider-gaea' exists, but the clientHeight of 'anderblokhoogte' differs from the height I see when inspecting this element. But also, the adjustment of the curblok.clientHeight does not give a change in height of the target element.
I already tried quite some options (other properties like 'style.height', 'offsetHeight') but no idea what mistake I make.

anderblokhoogte = document.getElementById('slider-gaea');
var curblok = document.getElementById('curiculum');
document.getElementById('curiculum').style.height = anderblokhoogte.clientHeight + 'px';
<div id="slider-gaea" style="height:100px;"> First Div Block </div>
<div id="curiculum"> Second Div Block</div>
You cannot set height using .clientHeight instead use .style.height and you need to lose the !important at the end as well.
Element.clientHeight is a read-only property.
Note: While HTMLElement.style is also a read-only property, it is possible to set an inline style by assigning a string directly to the style property (see example above).

Related

Get element's CSS value with Javascript

I'm trying to find a way to get an element's CSS height property, or actually, just tell if a height property is set.
The problem is, when I use
$(elem).css('height');
I get the display height of the element, but I'm trying to see if the element has a height property that was set in either a class, id, or directly on the div.
Any suggestions?
You can use height also.
$(elem).height(); // to get the height.
Also see this Q/A
if you want to get correct CSS value, i can advise don't use jQuery
if we have HTML:
<div id="elem" style="height: auto"></div>
we can write JS:
$('#elem').get(0).style.height // "auto"
if we have HTML:
<div id="elem"></div>
JS:
$('#elem').get(0).style.height // ""
universal function:
var height = function(elem){
return $(elem).get(0).style.height === "" ? $(elem).height() : $(elem).get(0).style.height;
}
Likely not the best way but I would just look at the outerHTML, see if a height value is set. If it isn't then it's in the CSS (or nothing is set).
s = $(elem)[0].outerHTML;
if (s.indexOf("height:") > 0) {
// inline style
} else {
// somewhere else
}
$( "div" ).click(function() {
you can check if height is defined for this div parent element or children using *this* reference. For now i am just fetching the height of the div which has been clicked.
var height= $( this ).css( "height" );
//If height is truthy
if(height){
//your code here
}
});
Hope this answers your query.
For more details..
The problem is what do you mean by 'is set'?
In vanilla javascript you can do:
element.style.height
This will return an empty string if no height has been set INLINE.
However, if a height has been applied via a stylesheet, it will still return an empty string.
The problem is, if you return a computed height by either .height() in jQuery or window.getComputedStyle(element).height in Javascript, then there is no way of telling if it was calculated by applying a style sheet (what you would call 'having a height property set'), or was generated by extending the height of the element to fit its contents (which you'd call 'not having a height property set').
---------------------Update----------------------
To make it clearer, I'm trying to see if the height of a div is a computed height, or if it a height that was defined in css.
A div can contain the height of it's children, or it can have a height set specifically on the div. The heights for either the children or the div in question can be set in a CSS file, style tag on the page, or on the div itself.
I'm trying to see if the div has a css set height property.
by pedalpete
---------------------Update----------------------
I understood your question, but perhaps my answer was a bit opaque.
There is nothing you can call that will tell you if an element has a style property applied to it by a style sheet. In other words, you can't do what you want to do.
The only thing you can find out (via element.style) is if there is an inline style declared.
getComputedStyle will tell you how high an element currently is, but it won't tell you how it got that way.
by Graham Nicol
Looks like there isn't an easy way of doing this, my method to resolve this is to hide the children of the div, and and check if the height of the div has changed. If it has, the height was not set, if it hasn't the height was set.
This fails when the div has nothing but text, but as this is a layout tag, it will likely always have sub tags.
var elHeight = $(elem).height();
$(elem).children().hide();
var checkHeight = elHeight===$(elem).height();
$(elem).children().show();
console.log(checkHeight);
if(checkHeight===false) return setSize($(elem).parent().height()/2);

Reliably return element's scrollHeight without using `scrollHeight` property

Using either plain Javascript or jQuery, I need to get the full height of a scrolling element. But the DOM property scrollHeight is apparently not 100% reliable.
I was envisioning temporarily giving the item a css height of auto, checking out its size, then returning the css to its prior value (which itself has problems--how do I get the css height:100% instead of height:1012px like jQuery .css('height') will return). But then I figured out that due to the way jQuery applies css styling directly to an element, simply applying the style '' returns it to its normal style-sheet-declared value, so theoretically I could do this:
$el.css('height', 'auto');
scrollHeight = $el.height();
$el.css('height', '');
But this isn't working. height:auto isn't overriding my element's original style of 100% and making the element take up its full desired height.
So now I'm thinking something more along these lines: use the position of the first child element's top and the position of the last child element's bottom to get the height. (I can adjust for padding and margin if necessary, this is just a proof of concept.)
function scrollHeight($el) {
var lastEl = $el.children(':last');
return (
lastEl.position().top
+ lastEl.height()
- $el.children(':first').position().top;
);
}
Some working in of Math.max($el[0].scrollHeight, $el.height()) could also be useful...
Is that a terrible idea? I can't be the only person who's ever needed to know the scrollHeight of a DOM element and have it be reliable, not changing as the item is scrolled, and working in all major browsers, as well as IE 8 (though it would be interesting to know a solution for IE 6 & 7).
Instead of
$el.css('height', 'auto');
Try -
$el.attr('style', 'height: auto !important');
I mention trying this becuase you say -
height:auto isn't overriding my element's original style of 100% and
making the element take up its full desired height.

Get content width of an element

offsetWidth isn't good enough for me right now, as this includes padding and border width. I want to find out the content width of the element. Is there a property for that, or do I have to take the offsetWidth and then subtract the padding and border width from the computed style?
Since this comes up first when googling but doesn't have an appropriate answer yet, here's one:
function getContentWidth (element) {
var styles = getComputedStyle(element)
return element.clientWidth
- parseFloat(styles.paddingLeft)
- parseFloat(styles.paddingRight)
}
Basically, we first get the element's width including the padding (clientWidth) and then substract the padding left and right. We need to parseFloat the paddings because they come as px-suffixed strings.
I've created a little playground for this on CodePen, check it out!
It sounds to me like you want to use getComputedStyle on the element. You can see an example of getComputedStyle vs. offsetWidth here: http://jsbin.com/avedut/2/edit
Or:
window.getComputedStyle(document.getElementById('your-element')).width;
I would suggest either scrollWidth or the clientWidth depending on whether you want to account for the scrollbar.
Check out Determining the dimensions of elements or the specification itself.
I have the similar issue where my parent element isn't the window or document... I am loading an image by Javascript and want it to center after loading.
var parent = document.getElementById('yourparentid');
var image = document.getElementById('yourimageid');
image.addEventListener('load'),function() {
parent.scrollBy((image.width-parent.clientWidth)/2,(image.height-parent.clientHeight)/2);
}
Whenever you set the src then it will scroll to the center of the image. This for me is in the context of zooming into a high res version of the image.

Get height of div dependent on text inside

I have a DIV with some text inside. But the height of the DIV starts at 0px, it also has an 'overflow:hidden'. After that i'm using an animation system to increase the height of the DIV. But i can't give the DIV a fixed height because the length of the text inside the DIV varies.
Is there a way to tell what the height of the DIV will be when its big enough to fit all content inside it?
I have done a horrible hack but see if this is good enough.
Basically you get the content height by setting the height to auto, then resetting it to zero and finally using your animation function, like this :
var tempHeight = $(".sample").css({"height" : "auto"}).height();
$(".sample").css({"height" : "0px"}).animate({
height : tempHeight
},1000);
Where .sample is the reference to the div with the variable text content. Check out the demo for a better understanding.
Pure Javascript Version :
document.getElementById("sample").style.height = "auto"; //The id of this div is 'sample'
var tempheight = document.getElementById("sample").offsetHeight;
document.getElementById("sample").style.height = "0px";
/*
Custom Animation function, Use tempheight to get the full content
*/
DEMO For The Jquery Version
Maybe you can try this:
Put the text inside another DIV like...
<div>
<div>some text</div>
</div>
Then animate the outer div (which as an hidden overflow) according to the height of the inner div (which has not an hidden overflow).
Hope this helps
Depending on what you're doing/using you don't need to know the height because setting it to "auto" will ensure it expands to fill the content.
However, you could also not set the heights to 0 until you know the height by using javascript to get it. For example in jQuery:
$("div").each(function()
{
$(this).attr("data-height", $(this).height()).css({"height": "0", "overflow": "hidden");
});
Now each div has an attribute called "data-height" that has the value of it's original height. You can then use this to expand the div when you need to.
Just before animating the showing of the div, clone the div and get rid of the height:0px constraint (change the height to auto, for example). Then grab the height of that cloned div for use in your animation.
In jQuery, this would look something like:
var myDiv = $('div');
var myDivClone = div.clone().insertAfter(myDiv).css('height','auto');
var myDivHeight = myDivClone.outerHeight();
myDivClone.remove();
myDiv.animate({height: myDivHeight}, 250);
Note the importance of actually cloning the element in question as opposed to just creating a new one and filling it with the same contents. You need to recreate the element exactly (other than the height modification you do afterwards), including classes, etc.
ALSO note the importance of injecting it into the DOM immediately after myDiv. This is so that the same CSS will affect it as affects myDiv at time of height calculation. The only potential exception to this is if you're using a :last-child selector in your CSS, and the clone ends up becoming the last child of the parent element. But that kind of issue should be easy enough to get around.
how about dropping the text in a off screen div first and getting the dimensions from that?
if(el.scrollHeight > el.offsetHeight || el.scrollWidth > el.offsetWidth)
{
//keep making element bigger
el.style.height = parseInt(el.style.height) + 2 + "px"
}
You could stick this snippet inside some sort of recursive function or while loop. Essentially you are checking to see if there is more content outside of the viewable area that a scroll-bar would show.

How do I get the CSS width value with Javascript?

I'm trying to calculate the width of an element so that when I use JavaScript to wrap a parent element around it, I can set the width of the parent to match the width of the child. The obvious $('#element').css('width'); isn't quite what I want because it only seems to return the calculated value in pixels. Is there some way that I can return the actual CSS value, whether it be 300px or 20% or auto, instead of the calculated value?
Here's generally how it's set up, but I'd like to know the CSS value of #child instead of the calculated value.
$(document).ready(function(){
$('#child').wrap('<div id="parent"></div>');
$('#parent').each(function(){
var childWidth = $(this).children('#child').css('width');
$(this).css('width', childWidth)
});
});
I don't believe you can do that. The best you will get is offsetWidth or clientWidth which return the calculated value, with and without counting margins, padding and borders.
You need to read the stylesheet itself.
See: How can I read out the CSS text via Javascript as defined in the stylesheet?
Everyone but IE supports window.getComputedStyle(element), which you can use like so:
getComputedStyle($('#child')).width; // returns actual width of #child
Doesn't help you with IE, though.

Categories