1

So I'm trying to make the height of my DIV's respond to the width of the window. The code:

var w = window.innerWidth;
var mathW = parseInt(w);
var divHeight = mathW*0.16;
document.getElementById('demoDiv').style.height = divHeight;

With the CSS being:

#demoDiv {
   margin: auto;
   background-color: red;
   width: 100%;
   height: 50px; //just to start with SOMETHING
}

Obviously I'm having trouble with that! I've played around with it and definitely can change the height if I just use regular integers, but even using parseInt('divHeight') did nothing for me!

4
  • 1
    document.getElementById('demoDiv').style.height = divHeight+"px"; Commented Feb 28, 2018 at 5:16
  • I don't know how in javascript, but in jQuery, you need to use resize() Commented Feb 28, 2018 at 5:16
  • Use CSS not JS for this. Commented Feb 28, 2018 at 16:48
  • You still haven't explained why you want to use Javascript for a task that is so easy to solve using only CSS. Commented Mar 2, 2018 at 0:01

2 Answers 2

3

You are calucalting the height in a correct way. But in order to set the height you need to add dimension to the value (say px).

You dont need to do parseInt as window.innerWidth is a property with typeof number.

var w = window.innerWidth;
var divHeight = mathW*0.16;
document.getElementById('demoDiv').style.height = divHeight+"px";
Sign up to request clarification or add additional context in comments.

6 Comments

Oh my god I'm an idiot!! Thank you I'll mark this as answered when it lets me.
Why would anyone do this with JS at all?
@connexo with what you will do this then?
height: 16vw;, see my answer below. It's what comes to mind first when presented with this task.
And how does that answers OPs question? He is asking why his code is not working... There are always multiple way you can take to reach a destination and most of the times multiple ways could be correct :)
|
0

What stops you from applying a pure CSS solution?

#demoDiv {
  height: 16vw;
}

Requires no Javascript, is much shorter and performs faster, and no need to apply any resize handler when window size changes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.