I am trying to get the full height of a JSX element in ReactJS using window.getComputedStyle, however I'd like to get the full value, height+margin, but I couldn't find a way.
When I use only height I don't get the margin value.
window.getComputedStyle(productsContainerRef.current).height
I know I can get both values separetely and sum them, but is there a straightforward way to do that?
I am getting the element using a ref, so, it wouldn't be possible to use the event to aim the target element and get outerHeight.
Is there a way to do that using getComputedStyle?
One option is to add the margins to the refs current height.
Example:
const outerHeight = (el) => {
var height = el.offsetHeight;
var style = window.getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
};
Related
I found this question to get the height of an element that has not height Attribute. But is it possible to get or calculate the height before it is rendert?
for example I have this Code:
var element = createElement("div");
element.style.width = "20px";
element.innerHTML = "XXXXXXXXXXXXXXXXXXXXXXXXX";
If I know the fontsize and other stuff like padding etc. , is it possible to get the height it would have if it gets rendert?
I need this because I need to know how heigh the element is before it gets rendert to change things that happens after that.
I want to make horizontally scrollable container which will keep child elements on the y-line (width more that 100% of the screen).
If the data was fixed I would calculate it before rendering and setup the width of the container. The problem is that my data is dynamic, I don't know the number of the child elements that will be added and their width. So I decided to add them dynamic to the container DOM as a children, but when I try to get their width after appending, the result is 0. What I am doing wrong, or if you have a better idea how to do that I will be glad to see your way.
This is what I am doing now:
GalleryContainer.prototype.addItem = function(newItem) {
var newItemDiv = document.createElement('div');
newItemDiv.className = 'thumbnail';
content = document.createElement('img');
content.setAttribute('src', newItem);
newItemDiv.appendChild(content);
this.galleryDiv.appendChild(newItemDiv);
this.galleryArray.push(newItemDiv);
// width, offsetWidth, all properties are 0
console.log(newItemDiv.style.offsetWidth);
console.log($(content).css('width'));
console.log($(newItemDiv).innerWidth());
}
EDIT:
I made a jsfiddle example with my problem and in the demo the width is not 0, it's the actual size that i need, so I have to look deeper for the problem.
http://jsfiddle.net/valkirilov/QaHn7/1/
bellow code is working, maybe your newItemDiv is not append into HTML Document:
var newItemDiv = document.createElement('div');
newItemDiv.className = 'thumbnail';
$('body').append(newItemDiv);
// width, offsetWidth, all properties are 0
console.log(newItemDiv.style.offsetWidth);
console.log($(content).css('width'));
console.log($(newItemDiv).innerWidth());
I have a div element, that has no defined width or height. It holds other elements, and molds on their size.
I need to get the final size of the div, without being able to check the sizes of the elements inside of it (dynamic elements).
I tried parsing all the properties of the object, but found nothing, all were "undefined".
Any thoughts?
Many thanks
Later edit:
I have
<div id="xxx" style="position:relative;">
aaaa
</div>
I tried:
var a = mydiv.style.width;
But it did not work.
I also tried:
var getKeys = function (obj) {
var keys = [];
for(var key in obj){
document.write(key+"="+obj.key+"<br>");
}
return keys;
}
getKeys(mydiv.style);
To show all the properties, but none had any info.
The jQuery solution works perfectly, but getComputedStyle was what I was looking for, as I can't use jquery here.
Sorry for the short information.
Based on no information whatsoever about what you were doing, I'd suggest that you should (if possible) use the window.getComputedStyle() approach, which finds the properties of an object as rendered by the browser:
var elem = document.getElementById('elemId'),
properties = window.getComputedStyle(elem, null),
height = properties.height,
width = properties.width;
If you have jQuery available, then you can simply use the width() and height() (or outerWidth()/outerHeight()) methods:
var height = $('#elem').height(),
width = $('#elem').width();
You don't give a whole lot of information. I'd suggest you edit your post with the actual code you tried using.
However, with JQuery:
$(DOMElement).width() //-- Element width.
$(DOMElement).innerWidth() //-- Element width + padding.
$(DOMElement).outerWidth() //-- Element width + padding & border.
$(DOMElement).outerWidth(true) //-- Element width + padding, border, and margin.
$('div').width() will return the width...
Normally when you have a div created in html. You can check its width with offsetWidth or style.width (if declared). However if the innerHTML is changed such that the width of the div is also change, neither of those functions work (not sure, but they haven't in my cases).
some code:
var div = document.createElement("div");
div.innerHtml = "asdfasdfasdfasdfsdfasdfasdfad";
alert(div.style.width); // this is nothing
alert(div.offsetWidth); // this is 0
How do you get the width of the div above?
I realize this is an old question, but for the many people landing here from google I'll provide it.
This is the way to do it in dojo 1.7+. With the geometry module you can get and set the width of the content (not including padding or border). This ignores box-sizing.
require(['dojo/dom-geometry'], function(domGeom) {
var myDivNode = dojo.query('div')[0];
var contentBox = domGeom.getContentBox(myDivNode);
alert(contentBox.w);
// This is how to set width/height
domGeom.setContentSize(myDivNode, {w: 100, h: 100});
});
Source: https://dojotoolkit.org/reference-guide/1.7/dojo/contentBox.html
you can't get width value of element that wasn't appended to document.
so you should append it to page, than you can get width,
here is a working demo
I have a textarea with the the text Hello World. I would like to get the height of this text.
I've tried to use:
var element = document.getElementById('textarea');
var textHeight = element.innerHTML.offsetHeight;
and:
var textHeight = element.value.offsetHeight;
But these don't give the numbers of the text, but the height of the textarea element.
element.scrollHeight is probably worth investigating.
If I was going to approach this (and I've not tested this at all), I'd set the textarea's height to 1px measure the scroll height and then reset the textarea's height.
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
Create a span element, set Span's innerHTML to "Hello World".
Get the span's offsetHeight.
var span = document.createElement("span");
span.innerHTML="Hello World"; //or whatever string you want.
span.offsetHeight // this is the answer
note that you must set the span's font style to the textarea's font style.
Your example will NEVER work because innerHTML and value are both strings. String doesn't define offsetWidth.
If you wish to get the height of selected text inside of a textarea, use selectionStart/selectionEnd to find the selected text of the textarea.
In jQuery there is no scrollHeight, so it needs a little workaround. the solution would be:
var areaheight=$("textarea#element")[0].scrollHeight;
$("#element").height(areaheight);
or shorter:
$("#element").height($("#element")[0].scrollHeight)
You can use element.scrollHeight (just like Patrick answered) but it needs some corrections (I'm using jQuery in example):
1) if your textarea has padding, you need to substract it (top & bottom).
2) if element has already set height, you need to set it to zero (just for measure then set it back, else it returns this height + padding)
var h0 = $(element).height(); // backup height
$(this).height(0);
var h = $(this).get(0).scrollHeight - $(this).css('paddingTop').replace('px','')*1 - $(this).css('paddingBottom').replace('px','')*1; // actual text height
$(this).height(h0); // set back original height (or new height using h)
There is no need of extra span with same css as textarea.
For anyone using React:
const textarea_ref = useRef(null);
const [idealHeight,setIdealHeight] = useState(0);
const [inputValue,setInputValue] = useState("");
useLayoutEffect(() => { // useLayoutEffect TO AVOID FLICKERING
textarea_ref.current.style.height = '0px'; // NEEDS TO SET HEIGHT TO ZERO
const scrollHeight = textarea_ref.current.scrollHeight; // TO READ THE CORRECT SCROLL HEIGHT WHEN IT SHRINKS
textarea_ref.current.removeAttribute('style'); // REMOVE INLINE STYLE THAT WAS ADDED WITH 0px
setIdealHeight(scrollHeight + 2); // NEEDS TO ADD 2. I THINK IT'S BECAUSE OF THE BORDER
},[inputValue]);
return (
<textarea
// USE idealHeight STATE TO SET THE HEIGHT
value={inputValue}
onChange={onChange}
ref={textarea_ref}
/>
);
PS: It still flickers sometimes. At least in Chrome.
You can get the text height by getting the textarea scrollbar height
const textarea = document.getElementByTagName("textarea");
const height = textarea.scrollHeight;
console.log({ height });
http://www.quirksmode.org/dom/range_intro.html
sorry that I can't be of more help.
the problem with you example is that inline text does not have a height, it only has a line-height, for it to have a height it needs to be in display block mode, so that all the lines are added to a block of text, even then it all depends on the width of the box and the font-size, font-family etc.
what ItzWarty suggests is getting the text selection and putting it in a div that has the same font and width as the textarea, which has display block and allows you to get its height.
I am not sure whether I interpret your question correctly, but I personally needed to know the exact height of each line of text. The line-height property does not have the right value (for example, in Safari, it will be rounded to the closest value when actually printing text).
This is my workaround. You should have the following code somewhere at the beginning of the document.
// set one row in the textarea and get its height
element.rows = 1;
var height1 = parseFloat(window.getComputedStyle(element)["height"]);
// set two rows in the textarea and get its height
element.rows = 2;
var height2 = parseFloat(window.getComputedStyle(element)["height"]);
// Now, the line height should be the difference
var inputLineHeight = height2-height1;
The variable inputLineHeight should contain the correct value, in pixel.