Javascript - getPropertyValue gives wrong height [duplicate] - javascript

This question already has answers here:
Get div height with plain JavaScript
(13 answers)
Closed 21 days ago.
let a = document.getElementsByClassName("d1");
let b = window.getComputedStyle(a[0]);
let c = b.getPropertyValue("height");
alert(c);
.d1 {
background-color: red;
padding: 20px;
}
<div class="d1">Test test test</div>
The above code alerts 18px but the height of the div element is actually 48px. It looks like that it doesn't take in consideration its padding. How can I alert its real height?

The CSS height property does not include padding. Try using .clientHeight instead, which does include padding. Here's from the docs:
clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present).
let a = document.getElementsByClassName("d1");
let c = a[0].clientHeight;
alert(c);
.d1 {
background-color: red;
padding: 20px;
}
<div class="d1">Test test test</div>

Related

How to get CSS height and width if they are in percentage value using JavaScript?

How to get CSS height and width if they are in percentage value using JavaScript?
Lets say the CSS rule:
.field {
height:50%;
width:25%;
}
What we tried:
let a = document.getElementById("field");
console.log(a.style.height)
This give me empty string. Is there any way to get height in percentage using JavaScript?
The height of an element a as a percentage of its parent can be calculated as
getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%'
This works however the styles of a and its parent have been set (through classes, through inline style setting). It is not the same as finding out whether the heights were set by a percentages or by other units initially.
Here's a simple example:
let a = document.querySelector(".field");
console.log(getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%');
.container {
height: 50vh;
width: 30vw;
}
.field {
height:50%;
width:25%;
}
<div class="container">
<div class="field"></div>
</div>
Height = a.offsetHeight
Width = a.offsetWidth
This gives height and width in pixels. Doesn't matter how it's declared in CSS.
in css rule,field is with dot = class and in js, you are trying getElelmentById.
Change .field to #field in css rule and try ...
#field{
height:50%;
width:25%;
}
You can use getComputedStyle
let elem = document.getElementById('field');
let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
console.log(ht)

How to dynamically get the length of a div using JQuery and JavaScript?

I am developing a web application using AngularJS. I find myself in a situation where I have a bar (with the css I created a line) that must dynamically lengthen and shorten.
I know that JQuery scripts are sufficient to do this. For example, if my css is like this:
.my_line{
display:block;
width:2px;
background: #FFAD0D;
height: 200px; /*This is the part that needs to dynamically change*/
}
I could in the controller resize the line (of my_line class) simply with:
$(".my_line").css("height", someExpression*100 + 'px');
The thing is, I would like to dynamically resize the line based on the size of another div element (Or, in general, any HTML element of my choice).
I don't know how to get (at run-time) the size of a certain page element in terms of height.
Only in this way I would be able to create a line that dynamically lengthens or shortens as the size of a div (or some other element) changes!
How do you do this? So I will avoid writing hard-coded the measures but I want make sure that they vary as the dimensions of other elements on the page vary
I hope this is helping:
$(".my_line").css("height", $("#referenceElement").height()*5 + 'px');
.my_line{
display:inline-block;
width:2px;
background: #FFAD0D;
}
#referenceElement {
display:inline-block;
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my_line"></div>
<div id="referenceElement">Hi, I'm 5 time smaller than the orange line!</div>
Here I am using the setInterval to track the div's height (you can do width as well) and storing it in a previousHeight variable and comparing it every interval
Then according to the comparison, it will determine if the height of the div has changed. If it has then it will change the height of the other div according to the height of the first div
You can create multiple variables and track multiple elements in the same setInterval
$(document).ready(function(){
var previousHeight = parseInt($("#my-div").css("height"));
setInterval(function(){ checkHeight(); }, 100);
function checkHeight() {
// Check height of elements here
var currentHeight = parseInt($("#my-div").css("height"));
if(currentHeight != previousHeight) {
previousHeight = currentHeight;
$("#dynamic-div").css("height", parseInt(currentHeight) + "px");
}
}
$("#button").click(function() {
$("#my-div").css("height", parseInt(previousHeight) + 5 + "px");
})
})
#my-div{
background: #000000;
height: 20px;
width: 20px;
}
#dynamic-div{
background: teal;
height: 20px;
width: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my-div">
</div>
<button id="button">Increase div height</button>
<div id="dynamic-div">
</div>

keep root div center to page when window size changed [duplicate]

This question already has answers here:
centering root div through percentage width in all kind of resolutions
(2 answers)
Closed 8 years ago.
Please refer below code
<div id="root">
<div id="child1">xxxx</div>
<div id="child2">yyyy</div>
</div>
css :
#root
{
width:86%
margin:0 auto;
}
#root div
{
width: 50%;
float:left;
border: 1px solid red;
}
it will center the "root" div center to page.but some resolution is not aligned (i.e.centered)
so am checking the javascript/jquery code instead of using media query (since am using iE8 browser -media not supported)
<script type"text/javascript">
if (window.screen.availWidth >= 1200 && window.screen.availWidth <= 1390 ) {
$("#root").css("width","92%")
}
else
$("#root").css("width","86%")
</script>
but when browser window is resized , div content misaligned not centered to page. how can i manitain the div to center for all resolutions as well browser window changed ?
i dont know what percentage of width need to be set for each time window is reszied.
How to resolve this.
Thanks,
No, need to use any script for keep in center, it is also done by CSS :
Here is DEMO
Try to put it in .resize() method:
$(window).on('resize', function(){
if ($(this).width() >= 1200 && $(this).width() <= 1390 ) {
$("#root").css("width","92%");
}else{
$("#root").css("width","86%");
}
}).resize();
Not sure but this might causing you issues:
#root
{
width:86% // <-------here you have a missing ';'
margin:0 auto;
}

Make a div half the width of another div

What i'm trying to do is make the title of a blog post exactly half the width of the blog description and align itself at 50% of the width of the blog description.
This is what i tried in JS:
var post_title_width = document.getElementById("post_desciption").offsetWidth;
var post_title_width = post_description * 0.5;
document.getElementbyId("post_title").style.width = post_title_width;
HTML:
<div class="post">
<span class="post_title">This is a test title, testing some javascript...........</span><br>
<span class="post_description">Hello this is a test description right here, just to test some code im trying to do</span>
</div>
I am not using css because i want to test javascript and learn how to use it efficiently.
If you really want to do it in javascript, you've got a few problems:
You're trying to target class names with getElementbyId
Your variable names are messed up
Spans are not block elements, so setting the width isn't applicable unless you set overflow and change the display to block or inline-block
http://jsfiddle.net/cmweU/
var post_description = document.getElementsByClassName("post_description")[0],
post_description_width = post_description.offsetWidth,
post_title_width = ( post_description_width * 0.5 ) + "px";
document.getElementsByClassName("post_title")[0].style.width = post_title_width;
Try this (example):
HTML
<div id="head"><div id="half"></div></div>
CSS
#head {
width: 300px;
height: 100px;
background: purple;
}
#half {
height: 100%;
background: green;
}
JS
document.getElementById("half").style.width = document.getElementById("head").offsetWidth / 2 + 'px';
JS for margin inner block at the center of it's countainer try to use this (example):
document.getElementById("half").style.marginLeft = (document.getElementById("head").offsetWidth - document.getElementById("half").offsetWidth) / 2 + 'px';

How to get the maximum possible width of a div?

I need to know how one can get the maximum possible width of a div. Generally, a <div>'s width is limited by it's parent, meaning that it can not be larger than a certain amount. How that certain amount can be calculated?
I need this to calculate if the text inside the current <div> has overflown, (since the only way to detect a text overflow is to compare it's current width to its current clientWidth).
Thanks!
A couple ways to do this, let's start with your div...
<div id='mr_cleaver'>
<div id='beaver'>Blah</div>
</div>
...and then someJavascript:
//Method One: Find the width of the div's parent
var max_beaver_width = $('mr_cleaver').offsetWidth
//Method Two: Max out the div, find length, return to original size.
var beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = "100%";
var max_beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = beaver_width + 'px';
//Method Three: Check for overflow
$('beaver').scrollWidth > $('beaver').offsetWidth ? alert("Over") : alert("Within")
Thanks Steve!
Your suggestions were very helpful. Although none of them worked for me(probably I didn't explain my situation very well), but using your hints, I could find a way to detect text overflow:
/* specifying the height of 'beaver'*/
var font_size= $('beaver').css("font-size");
font_size = parseInt(font_size.replace(/[a-z]*/gi,''));
var maxHeight = font_size + 4; // 4 is to make sure that the font fits in the maxHeight
/*now calculate current height*/
$('beaver').style.overflow-y:visible;
$('beaver').style.overflow-x:hidden;
var cuurentHeight = $('beaver').clientHeigth;
/* check whether overflow is occured*/
if(cuurentHeight > maxHeight){
//overflow has been occured
}
If you want the div to be 100 % in width with no space between the edges, you can try to add this simpel CSS style to the div:
<style type="text/css">
#FullWidthDiv { // EDIT
position: absolute; // If you use 'fixed' as position, then the div
display: block; // won't become smaller when the screen is at is smallest.
float: left; // The fixed position is good when you for example want the
width: 100%; // menu to stay in place.
background-color: #06F;
height: auto;
left: 0px;
top: 0px
}
</style>
<html>
<body>
<div id="FullWidthDiv"></div>
</body>
</html>
You can append a div into parent element to measure it.
var test = document.querySelector('#test');
var div = document.createElement('div');
div.style.width = '10000px';
test.appendChild(div);
var maxWidth = test.offsetWidth;
test.removeChild(div);
alert(maxWidth);
#test {
display: inline-block;
max-width: 100px;
}
<div id="test"></div>

Categories