I have an issue with jquery .css function. I am using this to get the actual height of elements whose height is set to auto. Code which i am using is :
$(this).css({ height: $(this).css("height"), width: $(this).css("width") });
The issue is, the .css function sometimes returns "0px" sometimes "auto" and sometimes actual height (which is the desired behavior). Can anybody please tell me what i am doing wrong here ?
$(this).css("height") gives you the a defined (or default) value, while $(this).height() gives you the actual, 'measured' height.
From http://api.jquery.com/height/:
Get the current computed height for the first element in the set of
matched elements or set the height of every matched element.
And from http://api.jquery.com/css/:
Get the value of a style property for the first element in the set of
matched elements or set one or more CSS properties for every matched
element.
$(this).css("height") will return the set value of the CSS height property.
To get the physical height of the element, call $(this).height().
Cannot see purpose of your snippet, but using jquery, use that code which at least is cross browser:
$(this).css({ height: $(this).height(), width: $(this).width() });
Related
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);
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.
I have a div called .A coded as height:auto that has a height rendered based on the text contained within. I have another div on the page called .B that I need to animate down using jQuery based on the height of the first div, .A.
I have attempted using the following jQuery function, without much luck. The idea was to have jQuery ascertain the height of .B then apply a padding to .B, however it is not grabbing the correct height. I have also tried using 'marginTop'
jQuery('div.A').animate({'paddingTop': jQuery('div.B').height()},500);
Desparate for help! Will pay with up-votes and generous compliments.
I think you need .outerHeight(true):
jQuery('div.A').animate({ paddingTop : jQuery('div.B').outerHeight(true)},500);
Description for .outerHeight() from docs
Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements.
Note:
The top and bottom padding and border are always included in the .outerHeight() calculation; if the includeMargin argument is set to true, the margin (top and bottom) is also included.
el = function(q) {return document.getElementById(q)};
el('strange').style.height = '100px'
el('strange').height = 2000
alert(el('strange').height) // 100?
alert(el('strange').getAttribute('height')) //2000? Wait.. What?
el is a shorthand of document.getElementById. Can someone explain me what's going on? I suspect that the height property is slightly different than the height attribute: they modified it so it returns the computed style. I'm not sure, because DOM 0 says that the property should be the same as the getAttribute, but the href property of an anchor doesn't match with the getAttribute in most browsers. And:
https://developer.mozilla.org/en/DOM/HTMLImageElement
The HTML:
<img id="strange" src="http://images.devshed.com/fcw/belts/fcw_forums.gif" />
The oddity isn't exaclty were you're spotting it. It comes from the fact that the call to the height attribute as a setter is creating a html height attribute in the img tag, and as far as I know, it's an attribute used only for canvas. There is no connection between this html tag and the dom value.
If i do the following:
strange.style.height = '100px';
strange.height = 2000;
console.log(strange.height); // 100
console.log(strange.style.height); // 100px
the output will be 100 and 100px the height on the DOM is correct. However, using the getAttribute search for the attributes in the html tag, therefor returning "2000".
EDIT
Ok i think i got it
There are 3 different stuff:
The css height, the height attribute, the height DOM value.
The easiest is the DOM value. It always return the img real height in css pixel. If set trhough css, it will be based on the css value, if set through attribute, it will be calculated from that.
Now the two other.
They both specify the img dimension. But the css value as precedence over the HTML attribute.
This is stated in the w3 recommandation. I quote
For
Inline replaced elements, block-level replaced elements in normal flow, 'inline-block' replaced elements in normal flow and floating replaced elements
It's stated that
If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic height, then that intrinsic height is the used value of 'height'.
Therefore, img (who are inline-block element I think) use the height css value, but if this one is set to auto (and it's the default) it uses the intrinsic height. And that is the html attribute.
So calling strange.height as a getter gets the DOM value, and as a setter, it sets the HTML attribute.
EDIT2 And to answer more exactly, you have 3 basic rules:
CSS prevails over attribute
DOM should be the same as attribute
DOM reflects the reality (here the real height)
You just can't follow the 3 rules if both CSS and attribute value are specified and differ.
The point is DOM should be the same. Here it can't be if there is CSS, so it has a different value.
As a side note, a nice explanation of the use of the height attribute here: http://reference.sitepoint.com/html/img .
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.