Using the height() method in jquery - javascript

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.

Related

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.

Set/Get style height in javascript

I try
console.log(document.getElementById('content').style.height);
prints nothing, just an empty line in console.
console.log(document.getElementById('content').clientHeight);
prints the height.
document.getElementById('content').style.height = '50px';
has no effect. I am in lastest chrome browser. I want to be able to read and set height, however set does not work. I want to use vanilla js. Any ideas?
Demo:http://jsfiddle.net/YTmNz/
JS:
function ChangeHeight(){
var e1 = document.getElementById("content");
e1.style.height = "400px";
}
setTimeout(ChangeHeight, 2000);
Unfortunately you cannot retrieve height with .style.heightunless you have already set that property before.
You can use jQuery to retrieve .height()
This is just a guess, but depending on what element content is you may also need to add display:block; to allow it to be given a height.
try to use
document.getElementById('content').offsetHeight
document.getElementById('content').offsetWidth
it will give the height/width of element;

javascript How to get dynamically height (when i resize browser)

I'm trying to get height from adjustable div because I'd like to add overflow style into css when height value will be greater than a set value. When you resize window height of this the div change. I'll explain this with some pictures:
The main problem is how to get it dynamically? I mean,when you resize your own window etc.?
In case you are able to use jQuery, I would suggest using the window.onresize method and compute the height of the div.
$(document).ready(function()
{
$(window).on("resize", function()
{
$("#myDiv").text("My height is " + $("#myDiv").height());
});
});​
Take a look at this fiddle I created for you: http://jsfiddle.net/9ftGe/
I hope this is what you wanted.
I think you're looking for monitoring the browser variables...
window.innerHeight
window.innerWidth
Whenever you check/call these variables you should get the exact window inner size and take it from there.
NB: These variables (constants to us) are case sensitive.

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

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.

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