Can't get height of hidden div in Firefox - javascript

I'm trying to get the height of an initially hidden div element in Netscape and Firefox using javascript (it works fine in IE). I have tried using MyElement.scrollHeight, MyElement.offetHeight, MyElement.style.height and many different ways of setting the element initially visible, getting the height and then hiding it again. I keep getting a value of 0. Any thoughts?

Correct me if I'm wrong (Which I may be), but from doing some research, elements with display: none have no height.
To get the height, you would need to unhide them, get the height, then rehide them. Issues like this have popped up in the past like so:
jQuery: height()/width() and "display:none"
jQuery: Get height of hidden element in jQuery
(Both jQuery examples, but you get the point)

Hidden elements in Netscape is not accessible.
you can set that position with styling hole of div out of your screen. for example move it to -9999 on top left. then you can access that's attributes like height and width.
you can also visible that element and get your attribute and hide it again, but it is not usual because your element will be show a little bit of the second and user maybe feel jumping on screen.
you should position it by setting style to "absolute" and "top" to -9999px or more (depend of your project height) and then get your element height and width with DOM and anythings that you want ...

Related

How to obtain clientWidth & clientHeight before DIV is visible

I want to obtain the dimensions of a DIV element (used to display a popup menu at the cursor position) while it's style.display='none;', however the dimensions of the DIV always return 0. The only way I seem to be able to get the dimensions is to make the DIV style.display='block;' at 0,0 and then move it to the required position, but that looks jumpy.
I've tried making the DIV visible outside of the visible screen area but that doesn't work. Is there a way to get the clientWidth and clientHeight values whilst the DIV is hidden?
If your DIV is not visible, you won't be able to get its dimensions.
However, there is a workaround. Your div has to be "visible", but that doesn't mean it's opacity and position have to be 1 and relative.
Set the opacity to 0 and the position to "absolute" and you'll be able to get the DIV dimensions.
EDIT
Since I think more people will have a similar problem, I feel I should explain my answer a little more.
If you try to get the size of a hidden element with JavaScript, you will always get 0.
So there are techniques to get the real size without displaying the element to the user. My favourite is the one I already wrote about above. Here are the more detailed steps:
you set the elements opacity to 0. This way it won't be displayed to the end user while you are getting the dimensions.
you set the element position to "absolute". This way it won't take up any space.
now it's safe to set the display to "inline-block".
you read the elements dimensions. This time you'll get the real values.
You set the display back to "hidden" and set the opacity and position back to its original values.
And now you have the size of a hidden element.
If you'd like to know the size of an element onscreen without it being visible you need it to be painted to the screen but not shown.
In order to get clientHeight and clientWidth you need it to be rendered so the calculations can be performed based on the screens current state (unless you have pre-programmed width and height, which I'm guessing you don't)
you can find out more information at MDN here
So you have options:
create your div offscreen using positioning (fixed or absolute) combined with z-index or opacity
use width: 0 and height: 0 and overflow: hidden then use scrollHeight and scrollWidth to find the overflow size
choose which option is best for your site, considering things like responsiveness and screen reflows and repaints

width of dynamically inserted div containing text

I have a script that dynamically inserts a div containing text in the dom. The text content is not known in advance.
I need to know the width of this div, but it seems that that the return value of document.defaultView.getComputedStyle(node, "").getPropertyValue("width") or node.offsetWidth cannot be trusted.
I used setInterval to log it, and the value changes over time. For instance, in my case it starts with 929px and then changes to 908px.
This div is in position absolute, it has whitespace nowrap, so I don't think it is being "pushed" by other dom elements or that it somehow changes once inserted.
Is there an elegant way to retrieve the width, or do I have to use an ugly setTimeout to retrieve it once the return value is stable ?
Try:
yourDOMElement.getClientBoundingRect()
This will return an object with top, left, right, bottom, height and width attributes. This should be cross-browser.
Note: If you are going to work with the position attributes (top, left, right, bottom, height) of the returned, take into account scroll offset if necessary.
Update: To ensure this works on older browsers that don't have the width/height attribute, calculate it subtracting right/bottom from left/top.
The viewport can change its size because of the scrollbar. Once the scrollbar appears, its width can no longer be used by the document. Force the scrollbar to exist before you measure the size by adding overflow: scroll or overflow-y:scroll to the <html> element.
The size of a block-level element is, by default, its container width minus margins and padding (even if it's positioned absolutely), which is ultimately the wiewport width unless you set a fixed width somewhere along the way.
Using jQuery, you should be able to do this:
var width = $("div-selector").width();
this is fairly easy?
open the page in a browser and press f12. With firefox there is a button "inspect element" on top and in chrome it's on the bottom. Click it and hover your mouse over it. This should give you the height and width in px. Never been wrong for me.
if it still doesn't show, click it and you can see it in the css panel of the console.

Applying position:absolute to a style via jQuery fails to center div horizontally upon first page load

This is a followup to my question here. I would like to understand why applying position:absolute to the CSS of a div via jQuery fails, while applying it in a static style works. Here are two jsfiddle examples:
Works: http://jsfiddle.net/jasper/Ty6Af/2/
No worky: http://jsfiddle.net/Ty6Af/3/
Note that the only difference between the two is where I apply position:absolute. Vertical centering always works, but horizontal centering does not work when the page loads for the first time. If you manually re-size the window the div will center correctly.
All of my testing has been on Chrome under Ubuntu thus far.
Anyway, I'm just now delving into the world of web development and these are exactly the kinds of 'quirks' that I need to begin understanding.
EDIT:
#Jasper found something interesting. If you make two calls to .css(), first applying position and subsequently applying a margin, it works. I would love to understand why. Here is an example: http://jsfiddle.net/jasper/Ty6Af/5/
So the issue is with how the width of the div is calculated by the browser depending on its position.
If the div is set to position : static (by default) then it's width is 100% of it's parents width and the element is not allowed to move around the page.
If the div is set to position : relative then it's width is 100% of it's parents width but it can be moved around with left.
If the div is set to position : absolute then its width is determined by the actual content of the div, for instance if there is only a 200px wide <span> element within the div then the div will be 200px wide.
You can test these observations by changing the CSS of your jsfiddle to specify position : relative (etc...) and remove the JavaScript that makes the div position : absolute, then use your Developer Tools to inspect the element and it's calculated width.
The problem with your code is that it sets the position : absolute at the same time it sets the margin of the element by using its width/height (which are calculated differently depending on the position of the element).
If you want to set the position of the div in JavaScript then you can do something like this:
$(function() {
//notice I cached the selector so it can be used in the future as well as set the position of the div
$signuparea = $('#signuparea').css({position : 'absolute'});
$(window).resize(function() {
$signuparea.css({
'margin-top' : '-' + Math.round($signuparea.height() / 2) + 'px',
'margin-left' : '-' + Math.round($signuparea.width() / 2) + 'px',
});
}).trigger('resize');
});
Here's a jsfiddle: http://jsfiddle.net/jasper/Ty6Af/8/
I believe the problem is that when you apply your left and right in your second fiddle, you have yet to add position absolute to the div. Hence, the browser has no idea what do with the left and right values and ignores them initially.
Practically speaking in your second fiddle, you only actually add the position:absolute on the resize trigger. So before you resize your actual div has no positioning.
If you instead add the position absolute on load it works fine:http://jsfiddle.net/Ty6Af/9/
Notice that if you give it position:relative from the start (like this http://jsfiddle.net/Ty6Af/11/ ) it allready applies both the left and right value. The reason you can't actually see the effect of "left" is because it is a block element.
I hope that answers your question, I'm not quite clear on where you are stuck.
http://jsfiddle.net/Ty6Af/7/ this should work, the trigger function in jquery has bugs with chrome so you have to run the function on load too.
The problem seems to be that position:absolute; negates the current layout and requires you to position it.....
See: http://jsfiddle.net/ZHaRD/
Which Jasper explains much more eloquently than myself!

Calculate element height the way slideDown() does

Have you noticed that by using jquery's slideDown(), even on elements with dynamic content, you always get the perfect height of the effected element. Which is, for me at least, impossible to do by simply animating the css height value. Mostly because there is no way for me to know how did the height of an element (with a display:none) changed, during a dynamic content (AJAX) update.
And since i've been working on some custom controls, i do need that capability to calculate things the way slideDown() does.
If you are inserting a new dinamically loaded content, it means you have that element in memory, so you can refer to it and know its height. You only have to read its height (or maybe outerHeight) and slide by that amount.
EDIT
Just give a height of 0 to the hiden item and overflow:hidden, so that the content inside it won't be sohwn, and it will retain its height.
http://jsfiddle.net/jgyLm/9/
You can try this after appending the dynamic content to the element.
$(element).height();
$(element).outerHeight();//if you need margin to be included pass true to outerHeight method

Javascript clientHeight and alternatives

I am currently trying to modify a Javascript function that "slides in" a <div>. The script as it is requires you to define the height of the div, so it is mostly useless in dynamically filled <div>s. I found some text on the clientHeight property in javascript, but it would appear that it doesn't support <div>s with display set to none (which is the method used to slide the div in). That makes sense, as the height of that div in the client window is nothing.
Basically I was wondering what other methods you all know of, or if there's a way to get around the clientHeight = 0 when display: none.
Thanks!
Oh, and here's the function I'm using:
function getDivHeight(objName) {
return boxHeight = document.getElementById(objName).clientHeight;
}
A simple solution is to set it's visibility to "hidden" and it's display to "block" and measure it. However, some modern browsers will manage to update the page layout during this short time and you will get a nasty flicker. The easiest way to overcome this is to place the element in an absolutely positioned container with overflow set to "hidden".
I've had luck cloning the element, moving it offscreen, then displaying it to get the client height:
var original = document.getElementById(some_id);
var new_item = original.cloneNode(true);
document.body.appendChild(new_item); // item already hidden, so it won't show yet.
// you may wish to validate it is hidden first
new_item.style.position = "absolute";
new_item.style.left = "-1000px";
new_item.style.display = "block";
var height = new_item.clientHeight;
EDIT: Looking through the jQuery code, they do exactly what Tsvetomir Tsonev suggests. jQuery temporarily sets the style to "display: block; position: absolute; visibility: none", and then measures the height, swapping the properties back after the measurement.
So, it looks like you're stuck with having to do something hackish, whether it's cloning the node or risking having it flicker in some browsers... I like Tsvetomir's suggestion better than my initial hack as it, at least, doesn't involve cloning a node into the DOM that you don't need. Either way, the element must not be set to "display: none" in order to measure it's height. Isn't the DOM wonderful? :-)
EDIT 2: Also worth noting that, after jQuery gathers the height, it adds allowances for padding, margin and border sizes, so you may need to as well.
Yes, an element that is not displayed on the page has no dimensions.
It kind of makes sense. Consider an element that has been created and filled with a bunch of text, but not yet added to the document tree. How high is it? Depends on font-size. How big is font-size? Depends where in the document that div is inserted; its parent font-size would inherit through.
Similarly for an element with “display: none”. It's not rendered, so it has no dimensions. Couldn't we ask “how high would this be if it were ‘display: block’”? Turns out no, because if it were displayed, that in itself could change the dimensions of its parent block, and then the dimension of displayed elements would be inconsistent with the dimensions of non-displayed elements!
The typical solution is to unset “display: none”, measure the height of the element, and then immediately re-set “display: none”. The browser won't redraw in the middle of a bit of JavaScript, so you won't see a flicker on the page.
I nkow you guys solved this a long time ago but I thought I should share this since it quite tricky to get the height of a hidden div tag.
heres what I did after reading your post,
I placed the div i want to slide inside a 1px height div with overflow set to hidden.
you dont even need to set the display of the inner div to none since it is already there and if you use offsetHeight it should return the proper height for all browsers and you can use that height to slide your div up an down.
PEACE!!!
In IE you could try scrollHeight, but I'm not sure if it will work or if it is cross browser.

Categories

Resources