5

I need to get browser window size , and set the window size to the div size in javascript.

i have 2 div elements if window size is 568px means, the div1 wants to 38% and div2 is 62%. In every size the both div wants to maintain the same percentage size.

Sathishkumar
  • 419
  • 2
  • 8
  • 20

3 Answers3

13

You can use this:

var width = window.innerWidth;
var height = window.innerHeight;

UPDATE:

To set the width of the two div elements when screen is equal or smaller than 568px you can do:

if(width <= 568) { document.getElementById('div_1').style.width = '38%'; document.getElementById('div_2').style.width = '62%'; }

Or using a CSS only based solution which I think is recommended and more simpler in this case, by taking advantage of media queries:

.container{
  width: 100%;
}
.div_element {
  height: 100px;
  width: 100%;
}
#div_1 {
  width: 38%;
  background: #adadad;
}
#div_2 {
  width: 62%;
  background: #F00;
}
@media(max-width: 568px) {
  #div_1 {
    width: 38%;
  }
  #div_2 {
    width: 62%;
  }
  .div_element {
    float: left;
  }
}
<div class='container'>
  <div id='div_1' class='div_element'>
    div 1
  </div>
  <div id='div_2' class='div_element'>
    div 2
  </div>
</div>
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
3

Use the following code to get browser window's height and width:

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
nashcheez
  • 5,067
  • 1
  • 27
  • 53
0

Why do you need JS to do this when CSS itself can do so? This piece of code will maintain the div sizes on every screen size

body {
  margin: 0px;
  height: 100vh;
}
#div1 {
  width: 38%;
  height: 100%;
  float: left;
  background: red;
}
#div2 {
  width: 62%;
  height: 100%;
  float: left;
  background: yellow;
}
#divMain {
  clear: both;
  height:100%;
}
#divMain:after,
#divMain:before {
  display: table;
  content: '';
}
#divMain:after {
  clear: both;
}
<div id="divMain">
  <div id="div1">
  </div>
  <div id="div2"></div>
</div>
Jones Joseph
  • 4,703
  • 3
  • 22
  • 40