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

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

Spacing vertically within a table cell

I'm currently experimenting with creating a vertical text-align: justify effect between divs. I am working with a structure that includes 4 div elements inside a td, like this: <td> <div></div> <div></div> <div ...

Using CSS to automatically adjust the width of a child div based on its content, rather than stretching it to fill the entire

I'm currently facing an issue with my CSS. Apologies for the vague title, but I'll do my best to explain it here. My problem lies within a parent wrapper div that is centered on the page. Within this wrapper, there is another child div containing ...

Odd behavior observed while running npm scripts in the npm terminal

Included in my package.json file are the following dependencies: "devDependencies": { "chromedriver": "^2.37.0", "geckodriver": "^1.11.0", "nightwatch": "^0.9.20", "selenium-server": "^3.11.0" }, "scripts": { "e2e": "nightwatch -c test ...

initiate colorbox resizing when parsley validation occurs

Currently, I am using parsley.js validation and colorbox to send a form via ajax. One issue I am encountering is determining how to dynamically resize the colorbox when validation errors appear. My goal is to activate this function when parsley detects er ...

Is it feasible to programmatically click a div button in C# using WebBrowser?

Exploring the capabilities of WebBrowser in C#, I came across a website that features a button without an ID, but rather nested within a div element. <div class="pc-image-info-box-button-btn-text pc-cursor"><i class="fa fa-heart" aria-hidden="tru ...

Connecting prop variables to component variables establishes a direct relationship between them

By assigning the props variable to a component variable, any changes made to the component variable will also reflect in the props... Parent Component: const prova = [ { 1: 'a' }, { 2: 'b' }, { ...

React not displaying images with relative paths

In the past, I used to import images in React like this: import person from '../images/image1.png' And then use them in my code like this: <img src={person} alt="" /> Now, for some reason, I want to directly specify the image pa ...

What is a sophisticated method to hide an element from view?

My dilemma involves a dropdown menu and a list of elements that are initially set to hidden using CSS. When an item is selected from the dropdown, it becomes visible. However, I am struggling with finding a way to revert the previously selected element b ...

Pattern matching for CSS class names

My current project involves creating a PHP function that will sift through CSS and JS files, swapping out class names and IDs in CSS selectors without touching the HTML elements or CSS properties themselves. Alas, my knowledge of regular expressions is sev ...

Using multiple main.js files with RequireJs in Play Framework 2.1.1 Java: A step-by-step guide

While working on a single-page app with AngularJs + RequireJs in Play Framework 2.1.1, I encountered an issue regarding the structure of my application. The project consists of two main sections - an admin dashboard and a normal website - both housed withi ...

flexbox: Two vertical icons tightly aligned without any space

Hey everyone, I've been working on this layout: https://i.sstatic.net/4Aye0.png Here's what I tried so far: Resetting padding and margin in the <a href> and in the <img src...> HTML container <div> <div className="pe ...

"Efficient Querying with MYSQL XDEVAPI Through Multiple OR (II) Requests

Currently, I am utilizing the XDEVAPI and attempting to incorporate the or(||) statement in JavaScript. However, it appears to malfunction after 1 or/(||) statements have been included. I need to fetch data from the database based on 5 distinct statuses: . ...

Utilize local .json data within a React component

Here is a snippet from my local .json file: { "results": [ { "id": 1, "title": "2 bedroom apartment to rent", "location": "30 South Colonnade London E14 5EZ", "description": "The building offers a communal lifestyle which co ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

Top-notch java tool for caching and minifying dojo, jquery JavaScript, and CSS files

In our project, we have downloaded the Dojo and jQuery libraries from Google CDNs. I am currently seeking a Java tool that can both cache and minify these libraries. The caching process should take place within the ROOT project of Tomcat. While I am awar ...

Using jQuery to toggle between open and closed states upon clicking

I've been working on a script that allows me to expand an element when clicked, change its content, and then minimize it again with another click Here's the jQuery code I came up with: $(".servicereadmore").click(function () { $('.myin ...

Incorporating fresh CSS styles through Selenium

I am attempting to showcase all the prices available on this page using Selenium and Chrome in order to capture a screenshot. By default, only 3 prices are visible. Is there a way to disable the slick-slider so that all 5 prices can be seen? I have tried r ...

The navigation bar struggles to display list elements without proper line breaks

Recently, I've been immersed in a web development project for a company. For the navigation bar, I opted to use the FlexNav JQuery plugin. While referencing the example on , I encountered an issue when attempting to add more than 5 list elements; they ...

Error: Attempted to access the 'state' property of an undefined object

I am working with the following function: extractCountries: function() { var newLocales = []; _.forEach(this.props.countries, function(locale) { var monthTemp = Utils.thisMonthTemp(parseFloat(locale["name"]["temperature"])); if(p ...