What is the method to obtain the dimensions of the browser window using JavaScript?

In my JavaScript code, I am trying to retrieve the browser window size and then set the size of a div element accordingly.

I have two div elements that should adjust based on the window size. For example, if the window size is 568px, div1 should be 38% of the size and div2 should be 62%. Regardless of the window size, both divs should maintain this same percentage ratio.

Answer №1

If you need to get the width and height of the window, you can use the following JavaScript code:

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

UPDATE:

In order to set the width of two div elements when the screen size is 568px or smaller, you can achieve that with the following JavaScript solution:

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

Alternatively, for a CSS-only approach using media queries which is recommended in this case, you can do the following:

.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>

Answer №2

Below is a code snippet to retrieve the height and width of the browser window:

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

var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Answer №3

Is JavaScript really necessary for this task when CSS alone can achieve the same result? The following code snippet ensures that the size of the divs remains consistent across various screen sizes.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Role-based dynamic layout

I am currently working on a website that requires user login functionality. To achieve this, I am utilizing materialise-css and Angularjs for the front-end development, while the back-end is powered by Java-Hibernate (as Spring is not an option in my case) ...

Converting HTML tables into arrays

I have JSON content that needs to be transformed into an array, specifically from a HTML table with cell values. Those cells should be combined into a single array for further use in the project. Struggling with the conversion of cell values into an arra ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

JavaScript Class experiencing issues with returning NAN when using the Multiplication method

Currently, I have a JavaScript Class with a multiplication method that aims to multiply all elements of an array excluding those that are undefined. To achieve this, I utilized a for loop to check the data type of each element (ensuring it is a number) and ...

Having trouble with CSS transitions not showing up correctly in Chrome. Any suggestions on how to resolve this issue?

While working on a static website, I attempted to apply a background-color transition to a button. Despite reviewing my code multiple times, I discovered that the issue was not with my coding. It seems like the browser is having trouble displaying CSS tran ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Is it a wise decision to provide the client with a new token just one minute before the expiration of the old one?

When monitoring my backend, I constantly check the remaining time before the JWT expires, which is set to 15 minutes. If there is only one minute left or less, I generate a new JWT and include it in the response header as a setToken. The front-end can then ...

Executing a JavaScript function from the form attribute value in HTML: Steps to follow

<html> <head> <script type="text/javascript"> function add() { num1 = 20; num2 = 30; total = num1 + num2; return total; } </script> & ...

Only reset radio buttons when the specific div they are contained within is closed, not when a different div is opened

I previously sought help for resetting selected radio buttons when closing a slideToggle in one of my jQuery toggle elements. You can find the question here: How to reset selected radio buttons when closing slideToggle? However, I am encountering a new is ...

Having trouble submitting a FORM remotely on Rails 3.0.3?

I am currently working with Rails 3.0.3 and using jQuery ujs for my project. My goal is to send a form remotely. The view template mains/index.html.erb where the form is located appears like this: ... <%= form_tag :remote => true, :controller => ...

Failed XHR: POST request in Cordova encountered an error

I am currently using cordova to develop a mobile application that includes a basic login form. The issue arises when I input the wrong username and password, as I receive a response from the server stating "INVALID INFORMATION" in XML format. However, upon ...

Guidance on loading JSON array information into highcharts using AngularJS

I am working on a project in Play Framework (play-java) where I need to display a bar graph using Highcharts. The Java API returns data in JSON format with a field called 'name' containing values like 'Data', 'Gadgets', ' ...

Developing a real-time form that syncs with a MYSQL database for automatic updates

I am currently working on developing a form with multiple drop-down menus. The first dropdown is populated with 'Customer Name' data retrieved from my MYSQL database. Upon selection, the second dropdown menu below it should display the available ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Searching with JQuery KeyUp - A step-by-step guide

Can you help me figure out why my live search is returning all results from the MySQL table no matter what I type? I am trying to get the previous request and initiate a new one on each keyup. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional// ...

Tips for implementing border-radius on Internet Explorer 8:

Similar Question: How to create rounded borders in IE8 using CSS? I typically use css border-radius for the design of my webpages. While they display well in Firefox, I am facing compatibility issues with IE8. Can anyone offer any assistance? Thank yo ...

How to have multiple versions of grunt coexisting on a single machine

I am involved in two different projects that have unique requirements for Grunt versions: Project A specifically needs Grunt v0.3.2 Project B requires Grunt v0.4.1 Both of these projects are managed in separate workspaces. Currently, I have Grunt v0.4. ...

Tips on choosing just the selected checkbox values

In my CodeIgniter view, I am utilizing AJAX to post data to my controller. <script type="text/javascript"> $(document).ready(function(){ // find the input fields and apply the time select to them. $('#sample1 inp ...

Sending an Ajax request to the MVC Controller results in a response of "NOT FOUND"

Trying to use AJAX to call a MVC Controller action with certain parameters has been successful in the past within this application. However, for some reason, THIS SPECIFIC ONE is not functioning properly. function deleteDetail(button, tab) { var i ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...