How to obtain clientWidth & clientHeight before DIV is visible - javascript

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

Related

Use div's height to determine another div's padding or margin-top

I am using the following jQuery to work out the width of a div (thats in %), to then tell another div to set it's height to that in pixels.
<script>
$("#top").height($("#left").width());
$("#bottom").height($("#left").width());
</script>
It's working really well. Now my next problem is, that I want my div called 'wrapper' to have a padding-top or margin-top of the pixel value it returns for the height. I tried changing 'height' to 'padding-top', but that didn't seem to work.
The end result is a web page with a series of 4 black div acting as a border around the edge, it calculates 5% of the with of the window, and that determine's the pixel value for how how the top and bottom black div's are. That way it's exactly even. Now I want my inside wrapper div, to start exactly that far down the web page too.
Use the jQuery outerWidth function to retrieve the width inclusive of padding, borders and optionally margin as well (if you send true as the only argument to the outerWidth method).
Tested Solution: Find height of a div and use it as margin top of another div.
$('.topmargindiv').css('margin-top', function() {
return $('.divheight').height();
});

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.

Can't get height of hidden div in Firefox

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

JavaScript - Need a way to set OuterHeight of the Element

I have an container element which is sort of a layout container for its children and based on some attributes I have to arrange children.
I need simple way to set outerHeight of an element, something like,
$(e).setOuterHeight(200);
jQuery's outerHeight does not set the height at all, indeed its a readonly method.
$(e).height(200); // this clips my element
In above method, I loose borders of input of type text.
My element's children are docked based on available space and some other criteria based on data that it holds, simple layouts like float,clear etc will not work because padding etc change dynamically based on sizes. I will finally end up using Table, even if I dont want to but have no choice, but anyway thanks for the help.
Now when element is sized to more then children then there is no problem, but sometimes container element may have lesser height then the children and that time, I need to increase the size.
function calculateSize(e){
var s = {
width: $(e).innerWidth(),
height: 0
};
var ae = new Enumerator(e.children);
while(ae.next()){
var child = ae.current();
// I have tried all alternatives
// for following lines
// child.clientHeight || child.offsetHeight
// $(child).outerHeight()
// $(child).innerHeight()
s.height += $(child).outerHeight();
}
if(s.height > $(e).height()){
$(e).height(s.height);
}
}
function layoutChildren(e){
....
/// for every child c
/// some steps before
var heightForChildren =
calculatedWithPadMarginBorder(availableHeight,c);
/// tried combinations
$(c).height(heightForChildren);
/// last statement fails for button
/// as button's padding cuts itself
/// removing padding in calculation
/// cuts other input elements !!
/// some steps after
....
}
I need some explanation of how to calculate runtime height/width including/excluding padding/margin/border etc and how to set it correctly so that I dont run into problems. I cant keep on trying all permutations combinations as I dont see a correct documentation even on jQuery website.
Fixed height calculations are fine, but this is kind of a dynamic element which resizes itself and arranges children in specific order.
Problem is there is no way to set outerHeight, when we set height/width of an element, the height/width is actually inner height/width without taking margin into consideration, while when we want to resize parent, we need outerHeight, but we cannot set back the outerHeight that easily.
My calculateSize and layoutChildren are two separate methods and two separate algorithms because parent will be resized to sum of all children's height. And then height is simply divided by no. of children stacked one above other. My calculation is perfect, but in my layoutChildren method I have "outerHeight" and "outerWidth" of element and have no idea on how to set it correctly by using jQuery or any other way.
.outerHeight( value )
version added: 1.8.0
you can use jQuery.outerHeight(value) to set the value of an element's outer height. Ex: $foo.outerHeight( 200 )
If you don't have a special requirement, a standard element by default sizes its height to match its children. If you style the to float:left or float:right its default width will then also be that to contain all its children.
Ok, this is strange but this is the Answer.
There are weird controls,
SELECT
BUTTON (INPUT[type=submit|reset|button])
WebKit Browsers
Padding and Border are considered as part of OuterWidth for all controls
Padding and Border must be added to Width as OuterWidth for all controls
Padding and Border are considered as part of InnerWidth for "weird controls"
Padding and Border must be subtracted from Width before setting the Width for all "non weird controls"
Non WebKit Browsers
Padding and Border are considered as part of OuterWidth for all non "weird controls"
Padding and Border must be added to Width as OuterWidth for all non "weird controls"
Padding and Border are considered as part of InnerWidth for all non "weird controls"
Padding and Border must be subtracted from Width before setting the Width for all "non weird controls"
I would be happy to help, but I simply do not understand your question.
In regards to the documentation of the dimensions methods of jQuery I found that http://api.jquery.com/category/css/ holds documentation on both innerWidth(), innerHeight(), outerWidth() and outerHeight().
I hope this helps, otherwise, try reading through your question, making it more obvious what you need the answer for.

Temporarily adjust height of element on hovering

I have a <h3> tag with limited height (100 px for example, position: absolute) and the text overflows it.
What I would like to do is slide it down over to the height that is needed when the mouse is over it and back to original height (100px).
I hope you understood what I mean
I don't think it uses slidedown() function for that and I am very weak in animate function. Any help please?
You can nest a div inside the h3 that contains the content and then use the h3 as a masking container (use overflow:hidden). When the user mouses over, fire a function that get's the height of the interior div (make sure to include any margins or padding). Then execute you height adjust animate function (In jquery, something like $('h3').animate({height: heightVar}); )The mouseout fires a function that restores the height of the h3 back to 100px.
Here's a sample: http://jsfiddle.net/XR9fb/
You can get the real height of the element with the scrollHeight property. Now, I don't really know much of jQuery, but I imagine you could just call animate to set the height CSS property to the scrollHeight of the element when the mouse hovers it, and return to the original height when the mouse moves out of it.
If the height of the element isn't fixed, you can salve the current height somewhere before displaying the full element, and when the mouse leaves the element you just restores this state.

Categories

Resources