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.
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.
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.
Is there a way to get the line-height of a span (or other inline element) in JavaScript/jQuery?
I need the exact computed line-height in pixels, not values of the sort 1.2em, normal or heuristics like fontSize * 1.5.
What I need to do is stretch the background of a span to fill the whole height of the line. I figured that I could add paddings to stretch the span, but for this I need the exact line-height. If someone can offer another approach, this would also be helpful.
An easy way to do this is:
var style = window.getComputedStyle(element);
var lineHeight = style.getPropertyValue('line-height');
This will get the calculate value of the line height without using jQuery and works on all browsers from IE9 onwards.
$("span").css( "line-height");
Retrieves the computed px value as a string "16px" for example. It uses IE's currentStyle or the standard getComputedStyle under the covers. Which is kind of surprising seeing as when it works as a setter it does elem.style.something = value which is a whole different thing.
assuming that the span is contained in a div.
you could set the div to position:relative
and the span as a block that takes 100% height.
In this way you will stretch the span as you want.
Example here
(note: to see the effect, change the background colour of the span to transparent. You should be able to see the red div.)
If your design allows for it, you can apply inline-block to the elements you are targeting and then use outerHeight ...
var inlineHeight = $('.inline-height').css("display", "inline-block").outerHeight();
//console.log('Inline Height:' + inlineHeight);
Suppose I have a div in my page, that doesn't have a width property manually set.
A user can resize his window, and so this div has, visually, a new "size" (dynamic). Is this new size (in px value terms) available somewhere? Like, "div.getCurrentSize" or something like that?
So, is it possible to get this width value from this div using something like javascript?
Look at the jQuery dimensions methods, e.g.
var w = $('#id').width();
Also note that it's not usually possible to obtain the dimensions of any element that's hidden. If you set the display property to none then the dimensions will all read as zero.
outerWidth
Description: Get the current computed width for the first element in the set of matched elements, including padding and border.
How about the standard javascript
(obj).offsetWidth