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.
Related
Ia have a div named "#idDayNrCell". I want to get its width then do some calculations and apply it to another div called ".event". I am using bootstrap so i need to apply !important aswell. I am new to javascript/jquery.
I tried something like this. But it didn't wotk
$(document).ready(function(){
var cellWDTstr = ($("#idDayNrCell").css("width")); //get width
var cellWDT = cellWDTstr.substr(0,cellWDTstr.length-2); //remove the "px" part
console.log(cellWDT);
var GunSayisi=2; //how long is the event (2 for example)
// after tihs things get complicated for me
// if the even is minimum 2 days i need a different width. calculated below
var wdtEnAz2 = ((cellWDT-30)*GunSayisi + 30*(GunSayisi-1)).toString();
console.log(wdtEnAz2);
var setWdt = GunSayisi>1 ? wdtEnAz2 : calWdt;
//after here it is expoerimental code which I am failed
console.log(setWdt);
setWdt+= 'px';
console.log(setWdt);
$(".event").style.setPsetProperty('width',setWdt,'important');
});
this is the html
Using ES6,
var width = "100px";
$(".event").attr('style', `width: ${width} !important`);
Add like this :
$('.event').attr('style', 'width: '+ setWdt +' !important');
You can use css property from jquery, please find below code snippet :
$(".event").css( "width", function(
setWtd ) {
return setWtd + '!Important';
});
I'm using JS with similar if statements in order to have Divs side by side. As the topic title suggests, can these if statements be combined or made more efficient in any way?
EDIT: The purpose of this code is to make all Divs the same height.
JS:
$(document).ready(function(){
$('.container').each(function(){
var firstDiv = $(this).find('.first');
var secondDiv = $(this).find('.second');
var thirdDiv = $(this).find('.third');
var fourthDiv = $(this).find('.fourth');
if(firstDiv.height() >= secondDiv.height()){
secondDiv.css('height',firstDiv.height());
} else {
firstDiv.css('height',secondDiv.height());
}
if(secondDiv.height() >= thirdDiv.height()){
thirdDiv.css('height',secondDiv.height());
} else {
secondDiv.css('height',thirdDiv.height());
}
if(thirdDiv.height() >= fourthDiv.height()){
fourthDiv.css('height',thirdDiv.height());
} else {
thirdDiv.css('height',fourthDiv.height());
}
});
});
Test page: http://www.gloryhood.com/articles/ztest.html
As the intention of the code is to equalise the heights of all the divs, you can negate the need for any if statements and use jQuery's map() to get all the heights, then use Math.max to get the tallest. Try this:
$('.container').each(function(){
var $divs = $('.first, .seconds, .third, .fourth', this);
var heights = $divs.map(function() {
return $(this).height();
}).get();
$divs.height(Math.max.apply(this, heights));
});
Note that the initial selector could be improved by adding a single common class to all the divs.
If your aim is to make all the heights the max height of any, the current code will not work (unless the first div is tallest).
Solution: check the heights for the max height first, then apply that height to them all.
$(document).ready(function () {
$('.container').each(function () {
var $divs = $('.blah', this);
var height = 0;
$divs.each(function(){
height = Math.max($(this).height(), height);
});
$divs.css('height',height);
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/8hko6of7/1/
Notes
I do not use your class names, but instead a common class on all the divs.
If your aim was something else, please explain in more detail :)
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();
I can get height in jQuery with
$(item).outerHeight(true);
but how do I with JS?
I can get the height of the li with
document.getElementById(item).offsetHeight
but i will always get "" when I try margin-top:
document.getElementById(item).style.marginTop
The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".
Live Copy | Source
Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
#yourElement {
margin-left: 10px;
}
<div id="yourElement"></div>
Here is my solution:
Step 1: Select the element
Step 2: Use getComputedStyle and provide the element to it
Step 3: Now access all the properties
const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)
It will give you margin with px units like "16px" which you might not want.
You can extract the value using parseInt()
const marginTopNumber = parseInt(itemTopmargin)
console.log(marginTopNumber)
It will give you the numerical value only (without any units).
How can I access the scrollHeight using mootools or some other property that contains the height so I can resize it to make an autogrow textarea?
Mootools offers a variety of Element 'dimension' functions that give you information on the scrollable and absolute element sizes. Full docs available here: http://mootools.net/docs/core/Element/Element.Dimensions
What you want to do is compare the return values of your element's getScrollSize() function to your element's getSize() function - in particular the 'y' member, which represents element and scrollable area height, respectively. Something along the lines of this should work:
var myElement = $('myElement'); // get a reference to your element
var scrollSize = myElement.getScrollSize(); // MooTools-specific function.
var elementSize = myElement.getSize(); // MooTools-specific function.
if (scrollSize.y > elementSize.y) {
// determine whether the scrollable area is greater than the dimensions
// of the element. If so, resize the element to match the scrollable area.
myElement.setStyle('height', scrollSize.y + 'px');
}
David Walsh created an excellent plugin for just this purpose:
http://davidwalsh.name/flext-textrea
Here's a simple method I'm using that expands but also contracts the textarea.
The issue you're always going to have is styling on the textare (padding/border).
The first thing to know is that getSize() will get the size of the textarea from absolute top to the absolute bottom, taking into account padding and borders. However, the actual style height of the text area .getStyle('height').toInt(), is the inside of the text box without padding and border. This is the part you need to be interested in as, when you set your height, it sets that, it doesn't set the full height of the textarea from absolute top to bottom.
Here's a working example, with a textarea that's styled (See Demo)
This will also resize the element correctly if you ran it inside domReady.
function expBox(el){
var e = $(el.id);
if(typeof(e._expBox) == "undefined"){
var v = e.value;
e.value = "";
var ss = e.getScrollSize();
var s = e.getSize();
var h = e.getStyle("height").toInt();
e._expBox = (s.y-h)-(s.y-ss.y);
e.value = v;
}
var k = event.keyCode || event.charCode;
if(k == 8 || k == 46){
e.setStyle("height","auto");
}
var ss = e.getScrollSize();
e.setStyle("height",(ss.y-e._expBox));
}
Demo:
http://jsfiddle.net/greatbigmassive/M6X5j/