Div width Javascript - javascript

Is there a way to get the entire width of a div including margins without using JQuery?
div.outerWidth
doesn't seem to work and clientWidth excludes margins.

As far as I recall, there is no single property value to get this.
Basically you need to get the margin width (left and right) and add them to your existing dimensions. Additionally, unless you are using box-sizing (By default you are not) you will need to add padding left and right as well.
You can use getComputedStyle to get the actual values you require. For example:
window.getComputedStyle(element, null).getPropertyValue("margin-left");
Edit:
I forgot border :P.... left and right border width as well...

Please have a look below code, there is being alert total width of div 220 including margin.
<style>
#myDiv{
width:200px;
height:200px;
margin:10px;
}
</style>
<div id='myDiv'>
</div>
<script>
var div = document.getElementById('myDiv');
var style = window.getComputedStyle(div);
var leftMargin = parseInt(style.marginLeft.match(/\d+/));
var rightMargin = parseInt(style.marginRight.match(/\d+/));
alert(div.clientWidth + leftMargin + rightMargin);
</script>

Related

How can I set the div to the height of two other divs with javascript while using bootstrap

I am using javascript to make images appear in a bootstrap template. They all have a with of 292.5px when on a full screen but I would like to make one of the columns set height to the height of two other columns put together. When looking for help I found this:
var right=document.getElementById('box').style.height;
var left=document.getElementById('slideshow3').style.height;
if(left>right)
{
document.getElementById('box').style.height=left;
}
else
{
document.getElementById('slideshow3').style.height=right;
}
But it wouldnt work for some reason. And I only need to change #box height to the height of #slideshow4 + #slideshow5
Thanks
---------------Update---------------
please see my jsfiddle Thanks
You almost got it right except that style.height properties are not straight numbers ie.. 10px or 100% so you cant compare the raw values, you must parseInt() them first or use .offsetHeight instead (or both) and then add the unit type back when setting them. Please note: .style properties ARE read/write. Also the .style.height property must be set in code before you can read it (so use offsetHeight instead) You are also missing the id attribute in your box div eg.. <div class="box" id="box" style="height: 185px;">
To fix your code above:
var rightHeight=parseInt(document.getElementById('box').offsetHeight);
var leftHeight=parseInt(document.getElementById('slideshow3').offsetHeight);
if(leftHeight>rightHeight){
document.getElementById('box').style.height=leftHeight+'px';
}else{
document.getElementById('slideshow3').style.height=rightHeight+'px';
}
The answer to your question:
var height1=parseInt(document.getElementById('slideshow4').offsetHeight);
var height2=parseInt(document.getElementById('slideshow5').offsetHeight);
document.getElementById('box').style.height=(height1+height2)+'px';
So, in your jsfiddle, box is a class, not an id, so it's .box and not #box.
If you want to set its height to be the sum of slideshow3 and slideshow4's height, use:
$('.box').height($('#slideshow3').height() + $('#slideshow4').height());
Try this function out
//sets the height of an element equal to the combined total height of the specificed slideshow id's
function setHeight(elementClass, slideshowIdArray){
var totalHeight = 0;
for(var i = 0; i < slideshowIdArray.length; i++){
totalHeight += parseInt($('#slideshow'+slideshowIdArray[i]).height());
}
$('.'+elementClass).height(totalHeight);
}
I forked your jsfiddle to provide a working example.
located here
I call this function once during intial page load and pass the box class to it along with an array of the two slideshows you want to match height.
I assume you want slideshow 6 to be flush along the bottom in relation to all other slideshows on the page, however, it seems that the H5 tag inside your box div has a margin set on it and this causes slideshow6 to be pushed slightly lower than the other slideshows. This can be adjusted using CSS (removing the margin), or the javascript can be altered to account for this. Your choice
Use jquery like this, It may help you
left = $("#left").height();
right = $("#right").height();
if(left<right)
$("#slideshow3").height(right);
else
$("#box").height(left);
I created a demo since you have not provided the HTML . Here is what I did
HTML
Please not the use of inline & block level elements
<span id="box">
<div id="cl1" class="c1"> Column 1</div>
<div id="cl2" class="c1"> Column 1</div>
</span>
<span id="slideshow3"> Column 3</span>
Javascript
var left = document.getElementById('box').offsetHeight
var right = document.getElementById('slideshow3').offsetHeight
if(left>right){
document.getElementById('slideshow3').setAttribute("style","height:"+left+"px");
}
else{
document.getElementById('box').setAttribute("style","height:"+right+"px");
}
CSS
span{
width:292.5px;
display:inline-block;
float:left;
}
.c1{
height:100px;
border:1px solid red;
}
#slideshow3{
border:1px solid green;
}
JSFIDDLE

Height auto div to expand height

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";

Set height of div in pixels based off width of browser window in % (jQuery or JS?)

I am trying to set up a black border around a webpage. For the left and right side, just making "width: 5%;" in the CSS is fine. But then I want JS/jQuery to work out how many pixels that is, and make that the height of the top and bottom div.
Is this possible?
Thanks.
This should work for you
var val = $(".leftAndRight").width();
$(".topAndBottom").height(val);
Or with one line:
$(".topAndBottom").height($(".leftAndRight").width());
You can determine the value for the border width programmatically, assign it to all four borders, and also refresh it any time you resize:
var width,
drawBorder = function () {
var body = $('body'),
width = body.width() * 0.05;
body.css('border-width', width + 'px');
};
drawBorder();
$(window).resize(function () {
drawBorder();
});
Demo
If you set the left and right width in your stylesheet and then use JS to give the same border width to the top and bottom, unless you use a resize function your left and right borders will change every time you resize but your top and bottom borders will remain fixed.
You can use .width() to find width without the border and .outerWidth to find the width including the border. I think .outerWidth also gives you the width with the padding you may have to subtract that.

Animate DIV to full height and toggle back to defined height

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.

Browser default padding

Browsers have default padding for HTML page.
For example my FF sets 8px margin of body element by default.
I can calculate default width padding for HTML page using
jQuery(window).width() - jQuery('body').innerWidth();
due to body element spans all available browser viewport width.
Also I have other browser which sets different values for width and height padding.
Could you propose way to calculate height padding?
Previous code will not work due to body inner height will return actual page content height and will not span all available height.
Do you really need to calculate the padding? The padding is defined in an element's css setting for padding and margin.
You can get these easily in jQuery:
// Select the body element.
var bodyElement = $('body');
// Get the paddings
var widthPadding = bodyElement.css('padding-left') + bodyElement.css('padding-right');
var heightPadding = bodyElement.css('padding-top') + bodyElement.css('padding-bottom');
// Get the margins
var widthMargin = bodyElement.css('margin-left') + bodyElement.css('margin-right');
var heightMargin = bodyElement.css('margin-top') + bodyElement.css('margin-bottom');
You can remove the default user-agent (i.e. the browser's) settings by defining in your css file:
body {
margin: 0;
padding: 0;
}
Bypass the problem and use a CSS reset.
With a good reset, you will not have to calculate these as they will be set by yourself.

Categories