0

I'm quite new to Javascript but thought that I should challenge myself to use it to solve an old problem of mine.
I'm trying to set the height of a div to the same as the width of it. Example:
The width is set to 50% and the screen is 1000px wide, the element will be 500px wide. I want the height to be the same; 500px.
I tried to achieve this using this Javascript code:

var layer=document.getElementById('layer');  
var layer_width=layer.width();  
layer.style.height=layer_width;  

The width of 'layer' has been set to 50% in CSS. The height is unaffected however. What am I doing wrong

Edited by efth

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by JorgeM
1

here is an example of the code to set the height of the div with an id of "layer". Keep in mind that when you get the width, you get just a value. When you assign that value to the height, you need to add the "px" string.

<!DOCTYPE html>
<html>
<head>
<style>
body {
width:1000px;
}
#layer {
width:50%;
background-color:#7F7F7F
}
</style>

</head>
<body>
<div id="layer">Hello World!</div>

<script>
var mydiv = document.getElementById("layer"); 
var layer_width = mydiv.offsetWidth;
document.getElementById("layer").style.height = layer_width + 'px';
</script>

</body>
</html>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.