I have the following elements in a HTML page:
<body>
<div style="height:100%; width:100%">
<div style="height:100px;"></div>
<div id="container" style="height:25%; width:50%">
</div>
Now I would like to get the height in pixels of the div container using jQuery (or plain JavaScript).
How can I do it?
$('#container').height() // returns `0`
In CSS, height as a percentage doesn't work unless the parent element also has height defined. And the parent's height won't work (if it's a percentage) unless its parent has height defined, and so on.
In this case, try adding this to your CSS:
html, body {
height: 100%;
}
Update: The other reason your code is returning 0 is because the DIV doesn't have any children (not even text nodes). If you added a child node, it would return the height of that child node, but it still wouldn't return the 25% value until you add an explicit height to all parents of elements that define height in percentages.
With the code you provided, "0" is the correct answer. -- As mentioned in a comment below : Divs are block by default. The reason this resolves to "0" is because in this instance, the container that it is deriving the "%"s from, are 0. So you are essentially saying : height = 0 * .25;
You need to either specify size of the div and its parent OR there need to be child nodes which grow the div's size naturally.
Then $('#container').height() will return a value larger than 0
You can do this Height_String= new String($('#container').css('height'))
the out put is 19px as string
or
You can do this Height_Int = new Number (parseInt($(#container).css('height'), 10))
the output is 19 as integer
$('#container').css('height');
The height is returned as 0 because the computed #container height is 0. Assigning a % height to a div without any relative fixed height will be assigned to 0.
See DEMO why it returns 0.
If your block has visible height other than zero, then probably you call jQuery.height() before page is loaded. Wrap your call into $(document).ready(function() {});:
$(document).ready(function() {
/* some actions */
var h = $('#container').height(); // Height that you need.
});
With simple JavaScript syntaxe it's works perfectly, but it's return the height in percent :
document.getElementById('container').style.height
Related
I have the JQuery following code:
$(".header").css('margin-top', $("#imgHeading").height());
It sets the element with the header class's top margin to the height of the element with the imgHeader id.
I want to run an if statement which checks if the header's top margin is equal to the imgHeader's height before it runs the actual function.
if (/* condition needed here Eg. marginTop != height */) {
$(".header").css('margin-top', $("#imgHeading").height());
}
I just need the condition, struggling to figure out what to do there.
You can try this:
var height = $("#imgHeading").height();
if(parseInt($(".header").css('margin-top'), 10) !== height) {
$(".header").css('margin-top', height);
}
This answer should work for everything except IE10 and lower. It works for percentage values too:
if(getComputedStyle($(".header")[0]).marginTop == getComputedStyle($("#imgHeading")[0]).height)
jsfiddle here
Please check: http://wixwebsite.seobrasov.com for reference.
My goal here is to achieve a body/wrapper div height according to the content instead of having a scrollbar for a 3500px height body on a 500px content.
I have a one page design with divs sliding in and out. There is a wrapper with overflow hidden and position relative that contains all the divs. Inside that, there are the divs having position absolute and height auto. Inside each div there are the content divs with height aut as well and they correctly expand to fit their content. It is all connected to a javascript that does the sliding. The whole thing only works if I set a fixed height to the wrapper div. Otherwise, having height auto on the wrapper or using javascript to set the wrapper div to the inner div height (which is height auto as well) makes the page not to expand & show any content AT ALL.
The first thing you would think about would be that the wrapper div does not expand height due to position absolute of the inner divs. That is only part of the problem. If I do indeed change the position to relative, it will only show part of the divs.
I have tried using javascript to set the wrapper div to take position from inner divs, but those inner divs also have height auto. And I cannot do the javascript on the content divs as there are more using the same class and having different heights, as they expand depending on content.
So the question that follows is:
Even if I achieve the wrapper div to expand height to its containing divs, wouldn't that height be the height of the biggest div? Since they are all on the same page?
Here is some code:
<div class="content-wrap">
<div class="dhome">
content
</div>
<div class="dabout">
content
</div>
etc.
.content-wrap{
overflow:hidden;
position:relative;
clear:both;
height: 3500px -> aiming for auto
}
.dhome,.dabout{
position:absolute;
right:-200%;
height:auto;
}
So far the only solution I'm seeing to this would be to place the content on different pages but I don't think that I'll manage to do the sliding.
Thanks in advance,
So I got this Javascript that does the animation:
function animate() {
var currentPageI = -1;
var pages = [
$('div.dhome'),
$('div.dabout'),
];
var viewsWidth = 1300;
var showPage = function(index){
if(index === currentPageI){return;}
var currentPage = pages[currentPageI];
if(currentPage){
currentPage.stop().animate({left: -viewsWidth})
}
var nextPage = pages[index];
nextPage
.stop()
.css({left: viewsWidth + Math.max(0,(($(window).width() - 980)/2))})
.animate({left: Math.max(0,(($(window).width() - 980)/2))})
currentPageI = index;
};
showPage(-1);
$('a.dhome').click(showPage.bind(null, 0));
$('a.dabout').click(showPage.bind(null, 1));
$(document).ready(function () {
animate();
});
First of all I have added the suggested Javascript at the end of this one and didn't do anything...after that I have added it into the animation script and used nextPage instead of the wrapper childNodes, and it still didn't do the trick. I will further look into this.
Thank you!
set an ID on the div with class="content-wrap"
var wrapper=document.getElementById(IDcontentwrap);
var childNode, childNodes=wrapper.childNodes, i, l=childNodes.length;
var maxWidth=0, maxHeight=0;
for (i=0;i<l;i++)
{
childNode=childNodes[i];
if (childNode.nodeType==1)
{
if (maxWidth<childNode.offsetWidth) maxWidth=childNode.offsetWidth;
if (maxHeight<childNode.offsetHeight) maxHeight=childNode.offsetHeight;
}
}
wrapper.style.width=maxWidth+"px";
wrapper.style.height=maxHeight+"px";
I am trying to animate the div to its full height when a button is pressed and come back to its original height if the button is clicked again. The full height of the div is auto as it contains text with different word counts. I tried doing the below codes but it does not work properly.
The CSS :
.category_brief{
text-align:justify;
height:100px;
overflow:hidden;
}
Example 1 : This code does not animate the div when opening to full height , but animates while coming back to old height.
$(".slide").toggle(function(){
$('.category_brief').animate({height:'100%'},200);
},function(){
$('.category_brief').animate({height:100},200);
});
Example 2 : The output of this code is the same as of Example 1
var toggle = true, oldHeight = 0;
$('.slide').click(function(event) {
event.preventDefault();
var $ele = $('.category_brief');
var toHeight = ((toggle = !toggle) ? oldHeight : newHeight);
oldHeight = $ele.height();
var newHeight = $ele.height('auto').height();
$ele.animate({ height: toHeight });
});
Example 3 : This code animates the div to its full height but does not toggle.
var slide = $('.slide');
var slidepanel = $('.category_brief');
// On click, animate it to its full natural height
slide.click(function(event) {
event.preventDefault();
var oldHeight, newHeight;
// Measure before and after
oldHeight = slidepanel.height();
newHeight = slidepanel.height('auto').height();
// Put back the short height (you could grab this first
slidepanel.height(oldHeight);
slidepanel.animate({height: newHeight + "px"});
});
If possible please provide a bit explanation also as i am a newbie..
Update : Solved by the idea from #chazm..
#chazm : thanks for the idea. I got it working by combining 1st and 3rd example ... Here is the code in case anyone needs it .
var slidepanel = $('.category_brief');
$(".slide").toggle(function(){
var oldHeight, newHeight;
// Measure before and after
oldHeight = slidepanel.height();
newHeight = slidepanel.height('auto').height();
// Put back the short height (you could grab this first
slidepanel.height(oldHeight);
slidepanel.animate({height: newHeight + "px"})
},function(){
$('.category_brief').animate({height:100},300);
});
Working with 'auto' height it always quite tricky. I think there are different issues in your examples.
1) Browser can't define correct 100% height. Possible solutions - define height to all its parents. Either set it to 100% (till html tag) or set closest parent as relative (because height is calculated from closest relative parent). If you want to animate div to 100% of the entire page - think of the absolute positioning
2)The same as above i assume
3)When this code supposed to toggle back it can't determine that it should become lower that it is now. Not absolutely sure why though. Probably because 'auto' height from 100% is set to something wrong. You may check in firebug what value it has on the computed tab after that function is toggled back. Probably it will give you a clue
Try to combine 2) and 3). The idea - if toggle is true (it shoud be lowered) then set newHeight = slidepanel.height('100').
The solution depends on your implementation needs. If you know that at first the div should be 100px etc in height and when you click, it maximizes to an unknown height, the following solution would work. If you had a structure similar to
<div class="outer">
<div class="wrapper">Content of unknown length here</div>
</div>
and css
div.wrapper { position:relative; height:100px; overflow:hidden; }
div.outer { position:absolute; height:auto; }
then you'd get a div that is 100px in height, with the content that doesn't fit in 100px cut off. Now when you press the desired button, you could get the height of the wrapper div, since it is a long as it's content is (even though you only see the top 100px) and set the outer div's height according to it. Like so
var newHeight = $('div.wrapper').height();
$('div.outer').animate({height:newHeight},200);
Which would then animate the outer div to display the whole contents. When you click the button again, you could just do
$('div.outer').animate({height:'100px'},200);
And you would again have only the 100px height.
I have the following function for calculating the height of .node. It then takes away the height of a possible image, .node-image, from the height of the .node, and sets a column, .node-content-column to have a height that is the difference (i.e. 500 - 50 = 450; column becomes 450 in height).
function initColumnSizer() {
imageHeight = $('.node-image').outerHeight(true);
resizeHeight = ($('.node').outerHeight() + 75) - imageHeight;
$('.node-content-column').removeAttr('style');
$('.node-content-column').css('min-height', resizeHeight);
$('.node-content-column').css('height', 'auto !important');
$('.node-content-column').css('height', resizeHeight);
}
This function gets called on page load, and resizes .node-content-column as expected.
It also gets called when a div within .node is toggled using jQuery.toggle(), but this calculation returns a larger number everytime, instead of reverting back to the original once this toggle is reverted.
Can anyone see where I am going wrong with this calculation? Or if I am going about it the wrong way?
Thanks in advance!
Karl
1) Maybe the problem is in outerHeight() function (it takes into account padding and border). Try using just height or clientHeight:
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
2) why do you need to cleanup the whole elements' style?
and then you try to assign height = auto, and after that: height = resizeHeight - what's the purpose for that ? check the logic of your code.
outerHeight(true) will return height + padding + border + margin. Possibly, you might want to use height() ?
Most possible is that "larger number everytime" have always constant difference -- for example 75.
May be you just have some dependecies between .node-content-column and .node?
If your nodes like .node-content-column, .node and .node-image are all singles, then it's better to use IDs for them -- not CSS classes.
I have a HTML element but I have not defined the width or height (or sometimes I may not have defined the right or bottom, but I did define the width & height) in CSS.
Do you know how I can use JavaScript to obtain either an elements width or height or right or bottom if I haven't set it?
#blockMenu { z-index: 0; padding: 10%; }
If I do the following, I know it wont work because I didn't set the width or right:
var width = document.getElementById("blockMenu").offsetRight - document.getElementById("blockMenu").offsetLeft;
Is there anyway to determine the dimensions & position of a element when I haven't set it?
If not what if I define the width; how do I obtain the elements width through JavaScript?
With JavaScript you can do
document.getElementById("blockMenu").clientWidth;
document.getElementById("blockMenu").clientHeight;
With jQuery you can do
$('#blockMenu').width();
$('#blockMenu').height();
Check working example at http://jsfiddle.net/7jteV/2/
if you have the option to use jquery, you can use the height() and width() methods.
You can use jQuery as well
$("blockMenu").width()
$("blockMenu").height()
http://api.jquery.com/width/
http://api.jquery.com/height/
document.getElementById("blockMenu").style.width
document.getElementById("blockMenu").style.height
Should do the trick