What is the Javascript equivalent for jQuery's width() function? - javascript

I want to be able to calculate the width, in pixels, of an element that has the width css property set to 'auto'.
I have tried element.style.width but didn't work because it returned 'auto'. I notices that the jQuery function width() returns the length in px, but I cannot use jQuery to solve this, because it is not available in my page. So, does anybody know an equivalent method for jQuery width()?
Thanks.

jQuery uses...
element.getBoundingClientRect().width
internally, it has some other stuff on top to deal with browser differences.
It returns an elements rendered size, where as .offsetxx returns sizes according to the box model.
element.getBoundingClientRect()
Is the most accurate way to get an elements "real" dimensions.
Here is a post by John Resig ( author of jQuery ) on the matter.
http://ejohn.org/blog/getboundingclientrect-is-awesome/

Wasted 2 hours on this.
For my case other answers did not work so combining others answers & my findings into one post with examples, for easy reading:
For an element like select, the width() in JQuery is same as clientWidth in JavaScript.
Sample code below, including output:
// Add jQuery library in HTML:
// <head>
// <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
// </head>
let eleId = 'myselectid1'; // NOTE: Provide your element id below
// jQuery
console.log( $('#' + eleId).width() );
// JavaScript
let ele = document.getElementById(eleId);
console.log(ele.clientWidth); // 58 // includes padding into calculation
console.log(ele.offsetWidth); // 60 // includes border size and padding into width calculation
console.log(ele.getBoundingClientRect().width); // 60 // includes border size and padding into width calculation
console.log(window.getComputedStyle(ele, null).getPropertyValue("width")); // 60px (note the px in value, you may also get values like 'auto') // all dynamic values for all CSS properties, IE>=9
console.log(ele.style.height); // empty string // if you set it earlier, you would get this
console.log(ele.innerWidth); // undefined // only works on window object, not on element like select/ div - fails in older IE<9
Hope that helps.

It basically comes down to .offsetWidth, but the jQuery code is a little more complicated due to cross-browser differences.

Related

Automatically max-height in JS

var DocHeight = $('.xxx').height();
$(".yyy").height(200 -DocHeight);
Hello,
Above I show scheme changing height element depends on another element height, and I have question, is an option do the same but with max-height?
Any css attribute can be set using .css (if you use jquery of course). So basically you do something like this:
$(".yyy").css('max-height', (200 - DocHeight) + ' px');
Note that in this case you have to manually add 'px' because .height() makes the conversion automatically, now you need to specify unit of measure (I'm assuming pixels from your example).
More examples here: http://api.jquery.com/css/
I also assumed that you wanted just to set the max-height. If you want also to get the max-height you can do it in a similar matter:
var DocHeight = $('.xxx').css('max-height');
$(".yyy").css('max-height', DocHeight);
Note that in this case DocHeight comes exactly as it is defined in css so something like '100px' or '10%'. You need to manually convert it to a number if you want to compute something based on it (as you can see I removed the '200 -' part from the second instruction since that would've been invalid because you would be subtracting a string from a number).

jQuery width(); not working properly

I think I'm going crazy :).
In my js file I have:
alert( $('.element').width() );
it will alert "867"...Which is wrong.
In the Chrome or Firefox console i type:
$('.element').width();
It responds with 567. Which is correct.
Am I missing something here. Should I be doing this a different way. Cause the code in the js file is messing everyting up.
BTW the element does have a width and float set through CSS -- width: 80% and float: left. But the browser consoles still give me the right width.
Thanks.
Try this:
$(window).load(function(){
alert( $('.element').width() );
});
try
$('.element').outerWidth();
Let me know if it helps
Sometimes you have to work with properties thinking about padding and margin extra sizes. Commands like innerWidth take care about the padding of the element, but outerWidth corresponds to the size counting it's border (and if receive true their margin too).
Take a look at this topic already closed, i hope this must help you: What is difference between width, innerWidth and outerWidth, height, innerHeight and outerHeight in jQuery
Cause
The .width() method is subject to the browser's reflow and repaint. The browser reflows and repaints the DOM objects during runtime. Visual changes to the HTML document also trigger reflow and repaint.
With these reasons, the .width() method will return a zero (0) value during browser states where reflow-and-repaint is still about to happen.
Solution
Always call the .width() method after reflow-and-repaint.
Common cases
Case #1. Document ready VS Window load
$(document).ready(function(){
// during this state, .width() is more likely equal to zero (0)
});
During the $(document).ready, DOM objects are ready to be manipulated. However, the browser is still doing reflow-and-repaint. Thus, there is a huge chance you will get .width() = 0
$(window).load(function(){
// during this state, .width() is more likely to have the right values
});
At $(window).load, DOM objects are ready to be manipulated and the browser is done with reflow and have repainted everything on the document.
Case #2. Hidden VS Shown
HTML
<div style="display:none">
<button>Foo</button>
</div>
jQuery
// still hidden
$('button').width(); // 0
// now shown
$('div').show();
$('button').width(); // right value
Again, to fix the zero width issue, always call the .width() method after reflow-and-repaint.

Using the height() method in jquery

I am new to jquery and am currently trying to set a variable equal to the height of some div with id="thing" before animating another div with class=".init_leftbar" by the same quantity.
var iHeight = $("#thing").height();
$(".init_leftbar").animate({top: iHeight + "px"});
However, this does not seem to be working.
if I just set "iHeight" equal to some number it will animate however.
I figured there has been some misunderstanding on my part as to how the "height()" method works.
Any help is greatly appreciated.
I would try to print $("#thing").height() in the browser console with
console.log($("#thing").height());
to see what is returning from the div.
I also noticed that .height() has some problems with absolute positioned divs given a display:block; style.
As documented in the Jquery API:
http://api.jquery.com/height/
// Returns height of browser viewport
$( window ).height();
// Returns height of HTML document
$( document ).height();
Consider running the script on document ready, allowing everything else to load first.
Also, you might get better mileage with outerheight(), which accounts for everything which can make up the height, including padding.
What about replacing:
$("#thing").height();
with:
$('#thing').css("height");
Be aware that css() returns string as "100px" and not 100 as height()
so you need to delete the '+ "px"' suffix.

Javascript - Get the width of an undefined element

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...

js style properties returns blank

I am trying to receive the original CSS width value of an object using JavaScript. However, if I use:
var originalWidth = document.getElementById(<idOfObject>).style.width;
It always returns blank. I've also noticed that any property I access using this syntax will return blank. I know for sure that the given element exists, since
alert(document.getElementById(<idOfObject>));
does shows me the right object.
Can anyone help me to solve this problem?
You probably try to get the value which was set in stylesheet, not directly like this:
document.getElementById(<idOfObject>).style.width = '100px';
If you want to get the width of the element you can use innerWidth property:
var width = document.getElementById(<idOfObject>).offsetWidth;
None of the previous answers were right.
The property you are looking for is clientWidth, but not in "style"
document.getElementById('idOfObject').clientWidth;
That will work both on "width" set with external css, style seccion or even inline style="width:80px"
General note: don't use <div width="500"> as it has no effect
The mentioned offsetWidth is the second best choice, but it does not return the exact width set in css, but that width plus border width
Other options like innerWidth that works with window object didn't work for me on divs.
This bizarre issue of realizing style.width not working properly, wasted 2 hours of my precious time :-), hope this answer shorts that time for anyone else in the future.
<div style="width:10%" id="mydiv" >
OR
<div style="width:10px" id="mydiv" >
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;
alert(curr_width);
This works for me
I tried it and I can get the value
http://jsfiddle.net/xyd95/
Well, unless the width has no unit
http://jsfiddle.net/xyd95/1/
I believe this will work
function getWidth()
{
x = document.getElementById(<idOfObject>)
return x.offsetWidth;
}

Categories

Resources