How to get the line height of a span? - javascript

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);

Related

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.

Width of an inline element

How do know width of an inline element, without adding to document?
With adding
var span = document.createElement('span');
span.innerHTML = 'Hello, world!';
span.offsetWidth; //0
document.body.appendChild(span);
span.offsetWidth; //70
How without adding to document?
Sorry for my english)
The width of an element does obviously depend on the styles used (e.g. on the font size), so it is impossible to compute the width of the element without knowing where it is in the DOM.
You may add it to some invisible element if you don't want it to show on the screen.
You cannot get a width of an element if the element itself is not part of the DOM.
You need to append it, but you may also position it outside the visible area (with position: absolute and a negative left/top property) and remove it once you got the width
Until the element is added, there's no way to know for sure how wide it is, because it depends on the styling context.
jQuery's width() method has a trick that it uses for display: none elements, I don't know if it will work for an element that hasn't even been added to the DOM (it works by temporarily showing the element, getting the width, then hiding it again).

How to auto resize text in fixed DIV according to the text's length?

I have a fixed width and height DIV, and I need to put text inside.
Problem is, this text can be in different lengths (letter-wise), so I dont mind to reduce its size once its overflowing.
But how can I do that?
Thanks
You can use window.getComputedStyle if you target modern browsers.
It returns a collection of all real style properties applied to an element.
When you assign your text, you can get its size and compare it with the size of the div. And reduce or increase the font size and measure again.In a few loops you should get the text in the DIV.
Here is a description: https://developer.mozilla.org/en/DOM:window.getComputedStyle
Long story short, you can't do it, since various platform and browsers render fonts differently.
And, there's no cross-browser, cross-platform method to calculate the font's rendered dimensions.
A Javascript "solution" is to check if the div is overflowing, and then bump up its size accordingly, something like
while (div.scrollHeight >= div.offsetHeight) {
div.style.height = (parseInt(fontSpan.style.fontSize) + 1) + 'px';
}

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