Adjust the size of a div element with JavaScript

Currently, I am facing a challenge with resizing a div with the id="test". My goal is to adjust the size of the div based on the height of the browser window subtracting 80px so that the element fits perfectly within the visible space without requiring scrolling. Here is the JavaScript code I have been using:

let calculatedHeight = document.body.clientHeight - 80;
let targetElement = document.getElementById("test");
targetElement.style.height = calculatedHeight + "px";

While setting the height directly like this works:

myElement.style.height = "600px";
, when trying to calculate it dynamically using document.body.clientHeight;, the issue arises because it returns a value without the "px" unit.

Answer №1

Combine the string "px"

myElement.style.height = Height + "px";  

and PS: utilize const, instead of let. Additionally, if Height is not a method-returning function (or a class), consider using it as lowercase height.

Employ CSS, not JS

#test{
   height: calc(100vh - 80px);
}

if your intention was to target 100vh (Viewport Height).

Illustration:

/*QuickReset*/*{margin:0; box-sizing:border-box;}

:root {
  --height-head: 80px;
}

#head {
  height: var(--height-head);
  background: #eee;
  position: sticky;
  top: 0;
  z-index: 1000;
}

#test {
  height: calc(100vh - var(--height-head));
  background: #0bf;
}

#main {
  min-height: 60vh;
  background: #aaa;
}
#foot {
  min-height: 20vh;
  background: #444;
  color: #fff;
}
<header id="head">HEADER</header>
<div id="test">GALLERY calc(100vh - 80px)</div>
<main id="main">MAIN</main>
<footer id="foot">FOOTER</footer>

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

Caution in Three.JS: Potential WebGL Issue with Texture Mapping in Material Creation

I'm facing a challenge with a JSON file (map.js) that I use to load my geometry and material settings. This file is quite large, making manual edits challenging. Here is a snippet of what it looks like: "materials": [ { "DbgColor" : 2632490, "DbgInd ...

One-time export feature similar to Typescript's export_once functionality

When I have the following code structure: File1.ts function someFunction(){...} export default someFunction(); and then File2.ts import File1 from "./File1"; File3.ts import File1 from "./File1"; My question is, will the export de ...

Exploring the world of jQuery AJAX alongside Google's currency calculator

I'm currently working on a code that utilizes an AJAX call to access the Google currency calculator. The expected outcome is to receive a JSON array that can then be used to gather exchange rate data. Here is the link: http://www.google.com/ig/cal ...

What are the steps involved in searching for a document in MongoDB with Mongoose?

Looking to query MongoDB documents that contain an array of objects and remove a specific object with a particular value? Here are some tips: Check out this example of a document schema: const mongoose = require("mongoose"); const LibrarySchema ...

The link background color is malfunctioning

I'm having trouble getting the background color to show for the active link class. The border changes to dashed, but the color remains the same. Can anyone help me figure out what's going on? I'm new to CSS and feeling a bit frustrated. Also ...

The act of linking an SVG image from the same SVG file can result in the disappearance

Can anyone help me figure this out? I'm facing a strange issue: <svg aria-hidden="true"> <use xlink:href="/assets/icons/utility-sprite/svg/symbols.svg#down"></use> </svg> <table> <tr> <td> ...

Using jQuery to modify a CSS property when a specific option is chosen

I'm currently working on creating an option dropdown menu and I've hit a roadblock trying to display a textbox only when the 'other' option is selected. Here's what I have so far: <span id="con-country"><label for="count ...

The toThrow() function in Jest seems to be malfunctioning

Even though my JS code throws the correct error, it still fails. Here is the relevant Jest code block: describe('operate', () => { test("works with addition", () => { expect(evaluate_expression("3+5")).toEqu ...

Require a selection from the menu on the right side needed

I am looking to have the logout link displayed on the far right when the other menu items are hidden. Currently, it is appearing in the center. Is there a way I can make it show up on the right? <div class="nav-content container"> &l ...

ReactJS components enhanced with bootstrap-table JS extension

I recently downloaded the bootstrap-table package from NPM (npmjs.com) for my ReactJS application. It provides great features for setting up tables and datagrids. However, there are additional js and css files needed to enhance its functionality. These inc ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Obtaining the value of an object with a key containing a space and special character in both the key and object name using Node.js

Here is the value stored in a variable named publicIdentifier. By using console.log("publicIdentifier", publicIdentifier);, I am able to retrieve the following value. Now, my task is to extract the value of MSISDN-MSISDN into a different variable ...

Empty MongoDB array persists even after POST request

After performing a POST request in Insomnia, my "games" array remains empty. What am I missing? UPDATE: New error after array.push({}) "errorValidationError: games.0.gameID: Path gameID is required., games.0.isGameActivated: Path isGameActivated is requi ...

Alignment of text to the left can be achieved by using either relative or absolute

After researching several solutions, none seem to solve the issue I am experiencing. My code is meant to create two red colored boxes as shown below: .redboxes-horz { width: 100%; margin-bottom: 50px; height: auto; top: 0; right: 0; } ...

jQuery - patience is required until all elements have completely faded away

I am facing a unique challenge: I need to trigger an action after two specific elements have been faded out simultaneously. The code snippet for this task is as follows: $("#publish-left, #publish-right, #print-run").fadeOut(function(){ //do something ...

Can you create a dropdown menu using information from one JSON file and have the selected option come from another source?

Recently, I came across this JavaScript code that is supposed to create a dropdown list of statuses: $.getJSON('/statuses', { ajax: 'true' }, function (data) { var html; var len = data.length; html + ...

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

Using NodeJS to generate a multipart/mixed response

I am faced with a particular situation: creating a multipart/mixed response in NodeJS with full control over the communication on both ends to avoid interoperability issues. A JSON file containing a list of nodes describing each ZIP file, for example: [{ ...

What's the most effective method for isolating elements in HTML to prevent one element from impacting another?

I recently created a password form in HTML with some nice functions. However, after making a small adjustment, the CSS is causing the elements to shift when clicking on different input boxes. This results in the labels on the form moving slightly up and do ...

What is the best way to show "no results found" message in a jQuery search list?

Everything is working smoothly. Does anyone have any suggestions on how to display a message saying "No results found"? This is the code I'm using: http://jsfiddle.net/UI_Designer/8p426fog/4/ $(".my-textbox").keyup(function() { var val = $( ...