This question already has answers here:
How do I retrieve an HTML element's actual width and height?
(16 answers)
How to get actual CSS property value of an HTML element node? [duplicate]
(5 answers)
Closed 4 years ago.
I am a beginner coder. It is probably very simple, but I tried to find the answer and have not succeeded. My question is why do width and height properties of div object return undefined while they are apparently 100px both?
In this topic is explained how to get .offsetWidth property. But as I understand it is not 100% the same as .width.
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var width = element.width;
console.log(element);
console.log(width);
}
}
div#test {
position: absolute;
height: 100px;
width: 100px;
background-color: black;
}
<div id="test"></div>
My answer
Thank you all guys for your answers. They pushed me to find my own simple solution which I hope will be helpful for such beginners as me. The answer is: div DOM object does not have .width and .height property even if you assign them in CSS and they work well. For this purpose it has .style.width and .style.height respectively. But even if you assign them through CSS they will not appear in element.style until you do it purposefully using Java Script. So to get width or height of the div element through JS first of all remove these properties from CSS. You will not need them anymore. Then assign width through element.style.width command and then you can easily get it whenever you want using element.style.width.
CSS
div {
position: absolute;
background-color: black;
}
JavaScript
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
test.style.width = "100px";
test.style.height = "100px";
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var width = element.style.width;
console.log(element);
console.log(width);
}
}
Use offsetWidth and offsetHeight
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
var offsetWidth = element.offsetWidth;
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;
console.log('element', element);
console.log('offsetWidth', offsetWidth);
console.log('width', width);
console.log('height', height);
}
div#test {
position: absolute;
height: 100px;
width: 100px;
background-color: black;
}
<!doctype html>
<html lang="en">
<head>
<title>test</title>
<meta charset="utf-8">
</head>
<body>
<div id="test"></div>
</body>
</html>
I think you need clientWidth and clientHeight.
Related
I wan't to make show() and hide() method like jquery have, but with pure javascript because I want to modify how the element show and hide. But after my attempts, I've changed where the code placed, changed the code, etc, still it won't work. Only for a few times it was work but it was inconsistent (when I try to run it through firefox, it work for once but never again). The display (block and none) and the exact width and height is work, but not the 2s transition. How to fix this?
<!doctype html>
<html>
<head>
<style>
div {
width: 0px;
height: 0px;
background-color: yellow;
border: 1px solid black;
display: none;
}
</style>
</head>
<body>
<div>
</div>
<button>
click !
</button>
<script>
var x = document.getElementsByTagName("button");
var y = document.getElementsByTagName("div");
x[0].onclick = fungsi;
function fungsi() {
if (y[0].style.display != "block") {
y[0].style.display = "block";
y[0].style.transition = "width 2s";
y[0].style.transition = "height 2s";
y[0].style.width = "100px";
y[0].style.height = "100px";
} else {
y[0].style.display = "";
y[0].style.transition = "width 2s";
y[0].style.transition = "height 2s";
y[0].style.width = "";
y[0].style.height = "";
}
};
</script>
</body>
</html>
I've messed around with your code and found that the reason for your problem was the switching from display: none; to display: block; and back. I've made a simple solution for this if you would like to use it.
Here is the modified CSS code.
div {
width: 0px;
height: 0px;
background-color: yellow;
border: none;
}
Here is the modified JS code.
var x = document.getElementsByTagName("button");
var y = document.getElementsByTagName("div");
x[0].onclick = fungsi;
var expanded = false;
function fungsi() {
y[0].style.transition = "all 2s";
if (!expanded) {
y[0].style.border = "1px solid black";
y[0].style.width = "100px";
y[0].style.height = "100px";
expanded = true;
} else {
var applyBorder = function () {
y[0].style.border = "none";
};
y[0].style.width = "0";
y[0].style.height = "0";
expanded = false;
setTimeout(applyBorder, 2000);
}
};
And here is a JSFiddle of this code for an example.
It could be something to do with vendor prefixes
So as well as having the following:
y[0].style.transition
You will also need:
y[0].style.mozTransition
y[0].style.webkitTransition
Try that, hopefully should work.
What you are doing is not animating show and hide with "pure javascript", it really is animating show and hide with CSS3. You are just setting the CSS properties trough javascript!
That being said, CSS3 transitions are not supported by every browser. For example even IE9 does not support it. Some other browser only work with prefixed versions of this property.
Try setting -moz-transition, -webkit-transition and -o-transition too.
For more details see: Transition browser support
However if you expect your animation to work across all major platforms I suggest you to use jQuery and try adjusting the settings to your desired behavior..
When you run
y[0].style.transition = "width 2s";
y[0].style.transition = "height 2s";
The first line will be overwritten by the second. So the transition goes only for width or height at a time, and when one of them is 0, the transition will be invisible.
You should set transition like this:
y[0].style.transition = 'width 2s,height 2s';
Or just set it for all properties that support transition:
y[0].style.transition = 'all 2s';
BTW, since the transition property is not changing, you should set them outside the changing part.
Another problem is, the <div> must be visible before the animation starts, otherwise it will have the desired width and height once become visible, and no transition is needed any more. visibility is another choice since an element with visibility: hidden still takes the place.
Here is a working copy of code:
<!doctype html>
<html>
<head>
<style>
div {
width: 0px;
height: 0px;
background-color: yellow;
border: 1px solid black;
/* Use visibility instead of display */
visibility: hidden;
}
</style>
</head>
<body>
<div>
</div>
<button>
click !
</button>
<script>
var x = document.getElementsByTagName("button");
var y = document.getElementsByTagName("div");
x[0].onclick = fungsi;
// set transition
y[0].style.transition = "width 2s,height 2s";
function fungsi() {
if (y[0].style.visibility != "visible") {
y[0].style.visibility = "visible";
y[0].style.width = "100px";
y[0].style.height = "100px";
} else {
y[0].style.visibility = "";
y[0].style.width = "";
y[0].style.height = "";
}
};
</script>
</body>
</html>
And something more, if you want to hide the element after the animation ends, setTimeout will work.
At the moment I'm trying to keep the footer at the bottom with Javascript. This is the result:
document.getElementsByTagName('body').onload = function() {KeepFoot()};
var element = document.getElementById('container');
var height = element.offsetHeight;
function KeepFoot() {
if (height < screen.height) {
document.getElementById("footer").style.position = "fixed";
document.getElementById("footer").style.bottom = "0";
document.getElementById("footer").style.left = "0";
document.getElementById("footer").style.right = "0";
}
}
My idea was to take the height of the div container and compare it with the height of the resolution of the pc. If the height of the div container is smaller than the height of the resolution of the PC, set to the div footer position: fixed;
But there is a problem in the script because it doesn't work.
Another question, the script that I created would be fine for keep the footer at the bottom?
HTML:
<html>
<head>
...
</head>
<body>
<div id="container">
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
</body>
</html>
The function is not being called on load. You can attach the function KeepFoot directly to the body tag like this Instead of calling like this:
document.getElementsByTagName('body').onload = function() {KeepFoot()};
or use my code from below:
(function() {
var offsetHeight = document.getElementById('container').offsetHeight;
var screenHeight = screen.height;
if(offsetHeight < screenHeight){
document.getElementById("footer").style.position = "fixed";
document.getElementById("footer").style.bottom = "0";
document.getElementById("footer").style.left = "0";
}
})();
"DOMContentLoaded" event only fires when document is ready similar to jquery's $(document.ready).
and, for styles you can use class instead of setting each style using javascript.
Code
document.addEventListener("DOMContentLoaded", function (event) {
var element = document.getElementById('container');
var height = element.offsetHeight;
if (height < screen.height) {
document.getElementById("footer").classList.add('stikybottom');
}
}, false);
#footer.stikybottom {
position: fixed;
bottom:0;
left: 0;
right:0;
}
<div id="container">
<div id="header">header</div>
<div id="content">Conent</div>
<div id="footer">Something in footer</div>
</div>
I thing your function works very well. maybe what is missing is the function calling.
function KeepFoot() {
if (height < screen.height) {
document.getElementById("footer").style.position = "fixed";
document.getElementById("footer").style.bottom = "0";
document.getElementById("footer").style.left = "0";
document.getElementById("footer").style.right = "0";
}
}
KeepFoot();
see this jsfiddle
If what you want is to maintain the footer on the bottom of the page, you must read this. cssreset.com/how-to-keep-footer-at-bottom-of-page-with-css/
You can do it without js.
I tried to use this code below, which adds buttons in slideshow on my site:
window.onload = function loadContIcons() {
var elem = document.createElement("img");
elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
elem.setAttribute("class", "up_icon");
var id = "views_slideshow_controls_text_next_slideshow-block";
if (id !== 0) {
document.getElementById(id).appendChild(elem);
} else console.log("aaaaa");
var elem1 = document.createElement("img");
elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
elem1.setAttribute("class", "down_icon");
var id1 = "views_slideshow_controls_text_previous_slideshow-block";
if (id1 !== 0) {
document.getElementById(id1).appendChild(elem1);
} else console.log("aaaaa");
}
On the front page, where I have slideshow everything works good, but on the other pages the error Cannot read property 'appendChild' of null occurs.
The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.
Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.
Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.
Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.
window.onload = function loadContIcons() {
var elem = document.createElement("img");
elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
elem.setAttribute("class", "up_icon");
var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
if (container !== null) {
container.appendChild(elem);
} else console.log("aaaaa");
var elem1 = document.createElement("img");
elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
elem1.setAttribute("class", "down_icon");
container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
if (container !== null) {
container.appendChild(elem1);
} else console.log("aaaaa");
}
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
This question already has answers here:
How do I retrieve an HTML element's actual width and height?
(16 answers)
Closed 10 years ago.
I tried to access the width of a div using javascript,
but every time it is printing NaN no matter what i set it.
I am new to javascript, what is wrong with my code ?
<html>
<head>
<title>hello</title>
<style type="text/css">
#base
{
width:300px;
height:30px;
background-color: black;
}
#scr
{
height:30px;
width:10px;
background-color: red;
}
</style>
<script type="text/javascript">
var magic = function()
{
console.log("inside magic")
var d = document.getElementById("scr");
var b = d.style.width;
console.log(b);
b = parseInt(b);
console.log(b);
}
</script>
</head>
<body>
<div id="base">
<div id = "scr" >
</div>
</div>
<br>
<button onclick="magic()">Magic</button>
</body>
</html>
You can use this function to do that:
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
The explanation of what's going on is here
Note that you must use element's id to access its style property through the function.
If you want to use selectors use document.querySelector() in place of document.getElementById()
you should try
d.offsetWidth
instead of
d.style.width
The code d.style.width returns the width explicitly specified by css while d.offsetWidth returns the computed width.
I'm trying to get my website to scale its width when the window size is changed.
JQuery:
$(window).resize(function() {
var w = $("body").width();
if(w-810 < 0) {
$("body").css("Left","0px");
}
else {
var width = w.toString() + "px";
$("body").css("Left",width);
}
});
CSS:
body {
background-color: #eeeeee;
position: relative;
left: 20%;
}
HTML:
<script src="scripts\jquery.min.js" type="text/javascript"></script>
<script src="scripts\myJavascript.js" type="text/javascript"></script>
....
<body class="body">
One thing I have noticed, if I select the body by class (change in jquery to "#body"), it always defaults to 0px for the width.
Any ideas?
If you want to get the body element by a class, you must use the '.body' selector. If you want to get elements with their id, use '#body'
Try to put the CSS in lowercase, better passing in an object as parameter. Moreover, try also to "cache" the body element in order to prevent several, unnecessary querys to the DOM tree:
var body = $('.body');
$(window).resize(function() {
var w = body.width();
if (w-810 < 0) {
w = "0";
}
body.css({ "left" : w + "px" });
});
The body class is '.body', not '#body'