What is the best way to adjust an element to match the height of the browser window?

I've coded a solution to ensure that the height of a section (#home) matches the height of the window, but it's causing issues.

Here is the code snippet I used:

// Adjust Home section height based on window height

function fitHomeToScreen() {
  var windowHeight = $(window).innerHeight();
  $("#home").css("height", windowHeight);
  alert(windowHeight);
}
$(window).load(fitHomeToScreen);
$(window).resize(fitHomeToScreen);

Every time I refresh the browser (regardless of the window size), the windowHeight remains the same. However, if I resize the browser slightly, the windowHeight doubles. This continues indefinitely. Here is an example:

902px [drag browser wider] 1804px [drag browser wider] 3608 ... and so on ...

Below is my complete code:

HTML

<html>
<head>

<link rel="stylesheet" type="text/css" href="style.css">

<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic|Montserrat:700|Merriweather:400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

</head>

<body>

<section id="main-menu">
  <a href="#home" class="logo"></a>
  <nav>
    <ul>
      <li><a href="#whatwedo">What we do</a></li>
      <li><a href="#howitworks">How it works</a></li>
      <li><a href="#team">Team</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
  </nav>  
</section>

<section id="home">
  <div class="content">
    <div class="headline">Headline.</div>
    <div class="explanation">Blah blah blah.</div>
  </div>

</section>

... More sections follow ...

</body>

</html>

CSS

/* CSS styles here */

Answer №1

After some experimentation, I discovered that the optimal approach is to avoid utilizing jQuery when determining the window height in order to prevent it from inflating to an absurd value.

Simply substitute $(window).innerHeight() with window.innerHeight, and you will achieve the desired functionality.

Answer №2

$("#home").css("height", "100vh");

This will adjust the height of the element to be equal to 100% of the viewport height.


LATEST UPDATE

It's worth noting that vh is now compatible with mobile devices, for more details please check: http://caniuse.com/#feat=viewport-units

Answer №3

Utilize the HTML DOM properties clientHeight and clientWidth for faster and more consistent results across different browsers.

function adjustHomeToScreen(){
      document.getElementById("home").style.height = document.body.clientHeight;
}
window.onresize = adjustHomeToScreen; 
document.addEventListener("DOMContentLoaded", adjustHomeToScreen); 
window.onload = adjustHomeToScreen; 

Check out this resource you might not need jquery for guidance on alternatives.

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

Circular dependencies in ES6 within a React project

After setting up a test project with React Native, I encountered an issue with circular dependencies being reported by Eslint. Despite this warning, the code still functions properly. This is my package.json configuration: ... "dependencies": { "axio ...

Managing onChange in a ReactJs project

Currently, my React tsx page features input boxes like the following: <textarea value={this.state.myData!.valueOne} onChange={(e) => this.handleValueOneChange(e)}/> <textarea value={this.state.myData!.valueTwo} onChange={(e) => thi ...

The auto search feature seems to be malfunctioning after clicking the button

Despite my best efforts, I am still unable to resolve this issue. I have tried numerous links and code snippets, but I am encountering some difficulty in finding a solution. THE ISSUE: I have an input field with type 'Text' for searching employ ...

Tips on waiting for a function to be executed by utilizing a promise to await its callback in Javascript/Node JS

I have a situation with two functions called async foo() and bar() Let's assume that the execution time of foo() is 5 seconds The execution time of bar() is approximately 10 seconds The code structure looks like this: await foo(); async foo(){ / ...

What is the best way to include an SVG in a ternary operation?

I have a complex custom input with autocomplete functionality as part of the customization. To maintain confidentiality, I will only share the snippet of code related to the suggestion drop-down in the autocomplete feature. I have two values - suggestions ...

Enhancing performance by dynamically updating DOM elements when they come into view during scrolling

Currently, I am in search of an efficient algorithm to dynamically load background-images for a group of <li>'s but I am encountering some efficiency issues. The code I am using at the moment is as follows: function elementInView($elem, vps, vp ...

24-hour countdown tool featuring a visual progress bar

Currently, I am in the process of developing an application aimed at assisting individuals in either forming new habits or breaking old ones. In this application, I am looking to implement a countdown timer that ticks down daily; with the help of this help ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

Is it possible for a dash in a GET variable name to cause issues with req.query in NodeJS Express?

I am currently developing a GET endpoint in Node.js using Express to handle the following variable: ?message-timestamp=2012-08-19+20%3A38%3A23 However, I am facing difficulty accessing it through req.query. Whenever I try to access req.query.message-time ...

The search suggestion function on my client's website is not functioning properly in Firefox, yet it works perfectly fine in Chrome and Safari

My client is facing an issue with their website's search suggest feature on the home page, located at . The problem seems to be specific to Firefox as it works fine on Chrome and Safari. Despite checking for any content blocking by Firefox, I couldn&a ...

Extract information from the table using $_POST

I possess a datatable within a form. Inside that table, there is a column designated for setting a price. Upon submitting the form on the same page, the $_POST data fails to populate. Consequently, I am in need of inserting it into the MySQL db post-submit ...

Using AngularJS to Extract JSON Data from a Table in an HTML Document

In the context of angularjs: I have a table with 2 fixed columns (ID & Comment) and additional columns that are added dynamically by the user clicking a button. The user can input data into the rows of this table, and I need to extract/ read this data. H ...

Changing the default download directory in Selenium using JavaScript

How can I use JavaScript to change the default download directory? I have a list of folders and one is named "C:\Study\Selenium". How do I update the location for downloaded files to this specific path in my code? chromeOptions.setUserPreference ...

Two tables arranged in a nested grid layout

Picture a bootstrap grid setup with an 8:4 layout. <div class="container"> <div class="row"> <div class="col-md-8"> </div> <div class="col-md-4"> </div> </div> </div> ...

Is it possible to merge two ajax request functions calling the same URL?

There are two separate calls to the same URL using .load(URL selector), but with different selectors assigned to them. Is there a way to merge these calls into a single one by storing the load results in a string, $('<div>') for example, a ...

Implementing ngClass on a paragraph with Radio Buttons for dynamic styling

In my home.css file, I created two classes named 'male' and 'female'. I also added two radio buttons with values 'male' and 'female'. My goal is to change the background color of a paragraph when I select one of thes ...

Passing PHP values to JQuery is a common practice in web

I have a PHP file named userAuthentication.php containing a function that returns either "true" for successful authentication or "false" for a failure. In addition, I have a login view called login.html which includes fields for inputting username and pas ...

Guide on invoking an Angular 1.5 component with a button press

Having just started learning Typescript, I'm struggling to figure out how to call my Angular component "summaryReport" on a button click. Here's a snippet of my code: Let's say I have a button that should call my component when clicked with ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...