Thinking about how to incorporate the value of a JavaScript variable into a CSS variable?

I am attempting to utilize Window.innerWidth and load the resulting value into a CSS variable, but it doesn't appear to be functioning correctly. What could I be doing incorrectly?

function myFunction() {
  var w = window.innerWidth;
  
  document.documentElement.style
    .setProperty('--window', w);}
:root {
  --window:0px;
}

div {
  
  height: calc(var(--window) / 2);
  background:red;
  
}
<div></div>

Answer №1

There are a couple of reasons why your code isn't working:

  1. The issue may be that you have defined the function myFunction but not actually called it in your code.
  2. window.innerWidth returns a value without units, so you need to add px as a suffix to make it a valid height value.

function myFunction() {
  var w = window.innerWidth;
  document.documentElement.style.setProperty('--window', `${w}px`);
}
myFunction();
:root {
  --window: 0px;
}

div {
  height: calc(var(--window) / 2);
  background: red;
}
<div></div>

Additionally, you can use the default value parameter of the var() function like this:

height: calc(var(--window, 0px) / 2);
This allows you to omit the :root ruleset if the --window variable is only used once.

Answer №2

To dynamically add a rule to the style-sheet, you can use either insertRule or addRule.

For more information, refer to "Add Rules to Stylesheets with JavaScript" by David Walsh.

// Learn how to add rules to stylesheets at: https://davidwalsh.name/add-rules-stylesheets
const addCSSRules = (sheet, selector, rules, index = 1) => {
  if (typeof rules !== 'string') {
    rules = Object.entries(rules).map(entry => entry.join(':')).join(';');
  }
  if ('insertRule' in sheet) {
    sheet.insertRule(`${selector} {${rules}}`, index);
  } else if ('addRule' in sheet) {
    sheet.addRule(selector, rules, index);
  }
}

const [ sheet ] = document.styleSheets;

addCSSRules(sheet, ':root', {
  '--window': `${window.innerWidth}px`
});
:root {
  --window: 0px;
}

div {
  height: calc(var(--window) / 2);
  background: red;
}
<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

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

What is the best way to transfer a list from aspx to javascript?

When populating a table by looping through a list, I aim to pass a row of data to my JavaScript code. If that's not an option, I'd like to pass the list and the ID number for the specific row. How can I achieve this? <%foreach(var item in Mod ...

Ionic2 - Ion-select malfunctioning on a particular page

I have encountered an issue with the ion-select component in my Ionic 2 app. Specifically, when navigating to a certain page, the ion-select does not display properly. Strangely enough, on other pages of the app, this component works perfectly fine. Below ...

A step-by-step guide to building an API page with Python

Hello everyone! I am just starting out with Vue.js and Python, and I have a question for you. My task is to create a basic webpage using Vue.js on the front end and Python on the backend, with Heidi SQL as my database. My team has requested that I create ...

Node.js route leads to a 404 error page due to a simple configuration

Trying to set up two separate routes using NodeJS with the express framework and Angular on the client side. The index page successfully renders at localhost:3000/. However, when attempting to render the login page by visiting localhost:3000/login, a GET / ...

Testing Jest with NodeJS involves simulating input from standard input (stdin)

I'm currently working on a command-line application that takes user input from standard input using the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, }); rl.on('li ...

What is the process by which photoswipe applies styles to blur an image upon clicking the share button?

If you want to see an example, check out this link: http://codepen.io/dimsemenov/pen/gbadPv By clicking on the Share button, you'll notice that it blurs the image (and everything else). Despite inspecting it closely, I still can't seem to figu ...

How can you disable an 'option' HTML5 element using the AngularJS methodology?

How can I disable an 'option' element in HTML5 using AngularJS? Currently, I am working with AngularJS v1.2.25. Here is the Plunk Link for reference: https://plnkr.co/edit/fS1uKZ <!-- CODE BEGIN --> <!DOCTYPE html> <html> ...

"Addclass() function successfully executing in the console, yet encountering issues within the script execution

I dynamically created a div and attempted to add the class 'expanded' using jQuery, but it's not working. Interestingly, when I try the same code in the console, it works perfectly. The code looks like this: appending element name var men ...

What is the appropriate title for the css class?

When creating a stylesheet for a website, should the CSS style names be related to the website or its content? For example, if my website is about web development, would it be correct to use style names like: #web-development-header .web-development-comp ...

Having trouble setting up npm package (fsevents) on Mac OS Catalina?

I'm facing an error when trying to run the npm install express --save command. Can someone assist me in resolving this issue? The error message is as follows: > email@example.com install /Users/delowar/Desktop/ytdl/node_modules/chokidar/node_modu ...

Responsive grid made with HTML and CSS to create dynamic DIVs

Currently, I am working on a project that requires a responsive page layout using divs. The layout should resemble a grid, with 3 columns that reorganize into 2 columns on smaller screens. Here is the basic HTML structure I have so far: <div id="main" ...

Adjust an OnDemandGrid utilizing dstore/Rest output through a POST request instead of a PUT request

I am facing a perplexing issue. I have an OnDemandGrid that is editable, and below it, I have a dstore/Rest collection connected to my backend (using PHP). While I can edit the data in the OnDemandGrid, I am unable to save it properly. When it reaches the ...

Execute a refresh command on a JQuery function in order to update the selection picker

Below is the HTML code I have created to allow for multiple options to be selected with live search capabilities. My knowledge of jQuery is limited, but I have included a code snippet to refresh the selections if more than one option is chosen. < ...

The button is disabled once inline CSS is applied to it

I was having issues with the CSS of my buttons being overridden by the user agent stylesheet. To fix this, I used inline CSS to override it. However, a new problem emerged where the buttons became unclickable. Here is the code I am using. Any assistance wo ...

Sending data from Ajax to PHP

I've gone through all the previous examples without success, and now I am facing a simple php question. You can find the example here. My goal is to click on a table and have the options displayed as follows: When I explicitly declare the table name ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

Is there a way to remove backdrop-filter: blur effect from elements within a div?

Having an issue with a CSS property. I have designed a modal that includes inputs and labels, and I want to blur the background content. However, the problem I am facing is that the blur effect is also being applied to all elements inside the container, in ...

Issue with non-responsive clicks in scrollable/List view on Android device due to CSS styling

Currently, I am facing an issue with my WebApplication where I have a dynamically generated very Long List using JQuery Mobile. The problem I am encountering is that I am unable to click on any item within this scrollable view. Although I can hear the soun ...