How to get offsetHeight then set it to 0 without callbacks? - javascript

Let's say I have div with height 100px.
I need to get element height, save value in variable and then set element height to 0.
My problem is that I get final style value - 0.
let height = element.offsetHeight;
element.style.overflow = 'hidden';
element.style.maxHeight = 0;
I know that there is some method to get current value, something like this:
let height = element.offsetHeight;
someBrowserRenderingOrPositionFunction();
element.style.overflow = 'hidden';
element.style.maxHeight = 0;

let height = element.getComputedStyle().height
The problem of element.style.height is that you get the height only if it has been written inside the html element tag with the style attribute.
getComputedStyle()
gives you the final style of the element as you see it on the webpage.

Related

Set element height equal to width using Vanilla javascript

I have a Nodelist of 10 elements which I am getting using below:
let elements = document.getElementById('all-photos-root').querySelectorAll('.photo-root');
This gives me a NodeList with 10 elements. The initial width on each element is set in percentage which is 25%. I want to set the height of each element equal to the width in pixels so that it always renders as a square.
I am doing it like below, but I always get width is undefined.
for (var i = 0; i < elements.length; i++) {
console.log('elements', elements[i], elements[i].style.width);
elements[i].style.height = elements[i].style.width;
}
Using Element#style will only get the properties that have been set inline (the properties in the style attribute, properties on the css won't be included).
If you want to get the currently active property you should use getComputedStyle.
You can also use offsetWidth, clientWidth or scrollWidth to get the width of the block in pixels (in number format).
var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var fooBar = document.getElementById("foo-bar");
console.log("Foo:");
console.log(foo.style.width); // 30px
console.log(getComputedStyle(foo).width); // 30px
console.log(foo.offsetWidth);
console.log("Bar:");
console.log(bar.style.width); // hasn't been defined using style attribue
console.log(getComputedStyle(bar).width); // 40px as defined in #bar css block
console.log(bar.offsetWidth);
console.log("FooBar:");
console.log(fooBar.style.width); // hasn't been defined using style attribute
console.log(getComputedStyle(fooBar).width); // will actually give the absolute width in `px` instead of the `50%` used in css block
console.log(fooBar.offsetWidth);
#bar {
width: 40px;
}
#foo-bar {
width: 50%;
}
<div id="foo" style="width: 30px;"></div>
<div id="bar"></div>
<div id="foo-bar"></div>
for (var i = 0; i < elements.length; i++) {
// width and height in pixels, including padding and border
// Corresponds to jQuery outerWidth()
let width = elements[i].offsetWidth;
// width and height in pixels, including padding, but without border
// Corresponds to jQuery innerWidth()
width = elements[i].clientWidth;
// Need to add the px at the end
elements[i].style.height = width + 'px';
}

Does Jquery/Javascript require an elem to be in the DOM to use .css()?

if(typeof this.description === 'undefined') {alert('No Description Set!'); return false;}
var tempDiv = document.createElement('div'); //create a div outside of the DOM
tempDiv.className = 'descriptionColumn formBox contentRow'; //make sure and use the
//same/equivlent class(s) to ensure accuracy
tempDiv.innerHTML = this.description; //insert the text
document.body.appendChild(tempDiv); //render div
lineHeight = parseInt($(tempDiv).css('line-height')); //get the line-height (make sure this is specified in CSS!)
//also we use Jquery here to handle any vender inconsistencies,
divHeight = tempDiv.clientHeight; //get the div height
tempDiv.parentNode.removeChild(tempDiv); //clean up, delete div
delete tempDiv;
return divHeight/lineHeight; //divide the height by the line-height and return
This code works, I am trying to calculate the number of lines in a div. That said I wasn't able to get the line-height until after I added this element to the DOM.
Origionally I planned on not adding it at all because I only use it to calcuate the number of lines in the DIV.
It makes sense that it wouldn't have a height until I added it, I am just wondering if I did the right thing, or if there is a way to get the line-height without adding it to the DOM in the first place.
Rendering/Layout decision by browser is taken by browser 2 conditions:
1)new element is inserted
2)some element's style has been changed
3)sometimes when window is resized
so until the element is in DOM Tree browser will not give Layout related style to it.
consider following code:
var div = document.createElement(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints "" (empty string)
why??
because window.getComputedStyle() returns the CSS style which are actully present in DOM(browser).
now,
document.body.appendChild(div);
var style = window.getComputedStyle(div);
console.log( style.color );//prints rgb(somevalue)
why??
because rendering engine has decided the CSS properties.
//One gotcha
var div2 = document.createElement("div");
div2.style.color = "red";
console.log( $(div2).css("color") ); //prints red because jQuery gives preference to div2.style.color over window.getComputedStyle(div2);
but console.log ( window.getComputedStyle(div2).color );//prints "" .... this proves that browser has not yet decided the properties of div2
Yes, it is. But ... if you have jQuery on your page, why don't you use it?
var $div = $('<div/>', {
class: 'descriptionColumn formBox contentRow',
text: 'Description',
css: {
position: 'absolute',
left: '-99999px'
}
}).prependTo('body'); // element wouldn't be visible for user on this step
//your calculations
$div.remove();

scrollheight of an element gives undefined value

In an element I've given CSS overflow: scroll;. Now in jQuery I want to have it's original height (containing all child elements' height). Children under this element are dynamically changing. I want to have height on scroll event.
Here is the code:
$("#container").scroll(function(e) {
scrollAll();
});
function scrollAll(){
var elemHeight = $("#container").scrollHeight;
var scrollHeight = $("#scrollbars").scrollHeight;
var ratio = elemHeight / scrollHeight;
$("#outup").html( elemHeight +" and "+ scrollHeight +" ratio "+ ratio +" = "+ ($("#container").scrollTop()));
}
Issue: It throws scrollHeight is undefined error. What's wrong?
There is no scrollHeight in jQuery - it's scrollTop():
var elemHeight = $("#container").scrollTop();
var scrollHeight = $("#scrollbars").scrollTop();
Alternatively if you want to use the native scrollHeight property, you need to access the DOM element in the jQuery object directly, like this:
var elemHeight = $("#container")[0].scrollHeight;
var scrollHeight = $("#scrollbars")[0].scrollHeight;
Or like this:
var elemHeight = $("#container").prop('scrollHeight');
var scrollHeight = $("#scrollbars").prop('scrollHeight');
If you are using Jquery 1.6 or above, use prop to access the value.
$("#container").prop('scrollHeight')
Previous versions used to get the value from attr but not post 1.6.
$('#div')['prevObject'][0]['scrollingElement'].scrollHeight;
Try to print console.log($('#div') which returns all properties related to that div or any HTML element

How to find the width of a div using vanilla JavaScript?

How do you find the current width of a <div> in a cross-browser compatible way without using a library like jQuery?
document.getElementById("mydiv").offsetWidth
element.offsetWidth (MDC)
You can use clientWidth or offsetWidth Mozilla developer network reference
It would be like:
document.getElementById("yourDiv").clientWidth; // returns number, like 728
or with borders width :
document.getElementById("yourDiv").offsetWidth; // 728 + borders width
All Answers are right, but i still want to give some other alternatives that may work.
If you are looking for the assigned width (ignoring padding, margin and so on) you could use.
getComputedStyle(element).width; //returns value in px like "727.7px"
getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log(rect.width);
}
You can also search the DOM using ClassName. For example:
document.getElementsByClassName("myDiv")
This will return an array. If there is one particular property you are interested in. For example:
var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;
divWidth will now be equal to the the width of the first element in your div array.
Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:
var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.
call below method on div or body tag onclick="show(event);"
function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.
function getStyleInfo() {
setTimeout(function() {
const style = window.getComputedStyle(document.getElementById('__root__'));
if (style.height == 'auto') {
getStyleInfo();
}
// IF we got here we can do actual business logic staff
console.log(style.height, style.width);
}, 100);
};
window.onload=function() { getStyleInfo(); };
If you use just
window.onload=function() {
var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}
you can get auto values for width and height because browsers does not render till full load is performed.

How to auto-size a textarea in height?

I set the width of a textarea to 100%, but now I need to know how many characters can fit in one row.
I'm trying to write a javascript function to auto-grow/shrink a textarea. I'm trying to keep from using jquery since I just need this one function.
My logic is to rows = textarea.value.split('\n'), iterate through rows and count += rows[i].length/textarea.cols, then count += rows.length, and finally textarea.rows = count. The only problem is that count is too large because textarea.cols is too small.
This function will set the height of the element (textarea, in your case) to the browser's default height. If that causes a scrollbar to appear, the height will be switched to the actually needed height.
function autoHeight(element){
element.style.height='auto';
element.style.height=element.scrollHeight+'px';
}
If you don't like the browser's default height, you can change that to some other default value of your own, of course.
Try this and enjoy:
var textarea = document.getElementById("YourTextArea");
var limit = 50; //height limit
textarea.oninput = function() {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, limit) + "px";
};
textarea {
width: 99%;
}
<textarea id="YourTextArea"></textarea>

Categories