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';
}
Related
I'm trying to make the elements on the page fade in on scroll. Easy enough right? Not for me.
HTML is a standard list.
CSS sets all elements to opacity 0 prior to scrolling.
I'm trying to use Native JavaScript only.
// get current page body
var actBody = document.getElementById('acts-body');
// on scroll function
actBody.onscroll = function(){
// get screen height
var screenPosition = window.innerHeight;
// get all text elements
var artistName = document.getElementsByClassName('artist');
// loop through all elements
for(var i = 0; i < artistName.length; i++){
// get each elements position from top
var positionFromTop = artistName[i].getBoundingClientRect().top;
// if element is in viewport add class
if(positionFromTop - screenPosition <= 0){
artistName[i].classList.add('txt-fadeIn');
}
else{
artistName[i].classList.remove('txt-fadeIn');
}
console.log(artistName[i]);
}
i think it should solve it
if(screenPosition - positionFromTop <= 0){
artistName[i].classList.add('txt-fadeIn');
}
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.
The code below causes that all divs with this class get padding including these divs which are not higher than 200, but I need to add padding ONLY to elements, which are really bigger than 200. The rest have to stay without padding. Does anybody know how I can get it?
var n = $('.class');
var height = n.height();
if (height > 200) {
n.addClass('padding');
}
Use .filter to select just the elements with the height you want:
$(".class").filter(function() {
return $(this).height() > 200;
}).addClass("padding");
In your code, n.height() just returns the height of the first element selected, it doesn't change what n refers to in the n.addClass() call.
Use each() function to iterate over the .class elements and check each height.
Then apply .padding class to those who's height is higher that 200px:
$('.class').each(function() {
var that = $(this);
if (that.height() > 200) {
that.addClass('padding');
}
});
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.
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>