assign a CSS style based on a JavaScript variable

I am looking to dynamically set the height of a cell in a table based on the window's height. I plan to retrieve the window's height using JavaScript and then incorporate it into the div style.

<script language="javascript">
var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth;
var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;

if (height>900 )
{
    set_height = "500px";
} else if (height>700 && height<900) {
    set_height = "400px";
} else if (height>500 && height<700) {
    set_height = "300px";
} else if (height>300 && height<500) {
    set_height = "300px";
}
</script>
<table border ="1">
<tr><td>
<div style="height: set_height">
</div>
</td></tr>
</table>

Can this be achieved?

Answer №1

To begin, make sure to assign an ID to the div:

<table border="1">
    <tr>
        <td>
            <div id="uniqueID"></div>
        </td>
    </tr>
</table>

Next, encapsulate your JavaScript within a window.onload function and specify the height based on the ID of your div:

window.onload = function () {
    var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth;
    var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;

    if (height > 900) {
        set_height = "500px";
    } else if (height > 700 && height < 900) {
        set_height = "400px";
    } else if (height > 500 && height < 700) {
        set_height = "300px";
    } else if (height > 300 && height < 500) {
        set_height = "300px";
    }

    // Target the div using the assigned ID and apply the specified height.
    document.getElementById('uniqueID').style.height = set_height;
} 

If you wish for this function to execute when the window is resized, switch window.onload with window.onresize:

window.onresize = function() {
    // same code as above
}

Don't forget to trigger it so it functions upon window load:

window.onresize();

Check out the Fiddle here

Answer №2

Here's the optimal approach to achieve this objective:

<script>
var adjust_height = "10px"
document.getElementById('demo').style.height = adjust_height;
</script>

<div id='demo'></div>

Answer №3

If you're looking for a way to make your content dynamic by having it change based on certain events, such as window resizing, you can achieve this by updating the style value accordingly.

For example:

window.onresize = function () {
    var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth;
    var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;

    if (height > 900) {
        set_height = "500px";
    } else if (height > 700 && height < 900) {
        set_height = "400px";
    } else if (height > 500 && height < 700) {
        set_height = "300px";
    } else if (height > 300 && height < 500) {
        set_height = "300px";
    }

    document.getElementById('myDiv').style.height = set_height;
};
window.onresize();

In this case, 'myDiv' is used as the ID of the DIV element:

<div id="myDiv">
</div>

You can view a working demo here.

Please note that if you only want the dynamic behavior once when the page loads, you can use the `window.onload` event instead.

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

The JS script is activated only when the window is resized

I have incorporated a touch image slide using an external library called SwipeJS. However, it seems to only function properly when I resize my browser window. Within the body, I have structured my images in the Swipe Container as follows: <div id=&apo ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

The confirm() function shows up before the background on a blank layout

I'm facing an issue where whenever my confirm() function pops up, the alert box displays correctly but then the background turns blank. I've tried various solutions like moving the entire if statement to the bottom of the page or at the end of th ...

Conceal/reveal specific sections of a table cell using jQuery

Here is a table I have: A header Another header First (some-text-initially-hidden) click row Upon clicking, it changes to: A header Another header First (some-text-should-be visible now) click row However, the text "some-text-initially-hi ...

What is the method for gaining access to variables and functions within bundle.js?

Hello, I am trying to figure out how to access variables in bundle.js. I want to experiment with variables and functions on the client side using JavaScript, but I'm having trouble calling them in index.html or the Chrome console. I use browserify to ...

Using jQuery to assess the values of all visible textboxes

Coming up with a suitable title for this question might be more challenging than the actual question itself. I've set up an error handler on one of my pages for posting to the database. It validates whether the input fields are empty and prevents exe ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

When using ReactDOM.render, make sure to provide a function as the last optional `callback` argument

I recently started learning React and I encountered the following error message after writing this code: ReactDOM.render Expected the last optional `callback` argument to be a function. `Instead received: Object` This is my code var Stats = Reac ...

Is there a way for me to determine which class has been selected using jQuery and JavaScript?

I created a list containing various links: <li class="link-1"><a href="#">One</a></li> <li class="link-2"><a href="#">Two</a></li> <li class="link-3"><a href="#">Three</a></li> .. Wh ...

Sorting through a collection by using a nested array

I've been working on optimizing my code to prevent making new http requests to my API every time I need to filter results. Currently, I have an array called pageContent that is populated with data from an API fetch when the page loads. Each object in ...

Unable to locate the div element during the Ajax request

I have implemented an AJAX call on a div with the class 'mydiv' as shown below: However, I am encountering difficulty in locating the parent div within the success section. <div class="mydiv"> <a href="/jewelry/asscher-cut-diamond- ...

Unable to stop the default form submission in Vue 3

Using the latest version of Vue 3 I am encountering an issue with preventing form submission. Here is my HTML form: <form id="app" @submit="onSubmit"> <input type="text"> <input type="text"> ...

Creating a Chart.js line plot with discontinuous sections (jumps)

Using Chart.js, I have created a line chart and am looking to avoid rescaling the x-axis for more sample points. What is the most effective method to showcase jumps when y axis values change abruptly? Ideally, I want to be able to assign two y values per ...

Using Django to load a template following an AJAX request

Currently, I am utilizing Django templates in one specific template where I load multiple divs with content by executing two AJAX requests simultaneously to improve performance. The main issue arises from a view element added at the end of this template, ...

Ensure that the top of a div stays in place as the user scrolls, and spans the entire width of the div

My goal is to create a sticky or fixed position header inside a div with a list, but I'm facing an issue where it only sticks to the width of the text. If I expand the width to 100%, it takes up the size of the entire page: import styled from 'st ...

Tips for displaying or concealing a div when hovering over a kendo-menu-item in Angular 8

I am seeking a way to conceal a specific div element upon hovering over a kendo-menu-item within an angular 8 project. Specifically, I would like to hide the div with the class "nav-flyout" when hovering over the kendo-menu-item labeled "what we do". Belo ...

JavaScript form submission failing to transmit updated data

I have been working on a JavaScript function that changes the hidden value of a form based on which button is clicked, and then sends it via post to a processing page. Even though I have confirmed that the value is being changed correctly, when the post i ...

updating the state value through an onChange event in the input field requires taking action by clicking outside the field

I've hit a roadblock trying to figure out how to update my button in real-time. Despite scouring various forums and threads for solutions (React form onChange->setState one step behind), I haven't been successful in resolving the issue within ...

What is the best way to transform URL images on a webpage into media library images in WordPress?

Having trouble converting HTML Static Sites to WordPress because images are hosted through HTML SRC Code. After conversion, no one can see the images in visual format on pages during editing. Is there a way to convert all image links inside pages to media ...

Provide the email address to use on the forum

Is there a way to code an email address in HTML that will be invisible and undetectable by forums? Thank you in advance. I'm looking for a more advanced solution like this one! <h>mariaburkke76</h><h><h><h><h>< ...