Transform JavaScript variables into CSS variables

Similar Post:
Avoiding repeated constants in CSS

I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript, I am facing challenges in sending them to my CSS variables efficiently. Is there a way to achieve this seamlessly? Below is an excerpt from my JavaScript code:

<script type="text/javascript>
<!--

  var viewportwidth;
  var viewportheight;

 // Standard compliant browsers (Mozilla/Netscape/Opera/IE7) use window.innerWidth and window.innerHeight

  if (typeof window.innerWidth != 'undefined')
  {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
  }


 else if (typeof document.documentElement != 'undefined'
 && typeof document.documentElement.clientWidth !=
 'undefined' && document.documentElement.clientWidth != 0)
 {
   viewportwidth = document.documentElement.clientWidth,
   viewportheight = document.documentElement.clientHeight
 }


 else
 {
   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
   viewportheight = document.getElementsByTagName('body')[0].clientHeight
 }
   document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
//-->
</script>

In terms of CSS, my attempt at quickly integrating the JavaScript-derived values has not been successful:

@variables{
ViewWidth:'+viewportwidth+';}

@variables{
ViewHeight:'+viewportheight+';}  

html{
max-width: var(ViewWidth);
max-height: var(ViewHeight);}

It seems like there might be an error in the syntax of the variable declarations. I structured it this way to indicate my objective of passing JavaScript variable values to CSS smoothly.

Answer №1

Perhaps you are seeking a solution like the following:

let mainElement = document.documentElement || document.body;
mainElement.style.maxWidth = mainElement.clientWidth + 'px';
mainElement.style.maxHeight = mainElement.clientHeight + 'px';

Answer №2

If you're looking to dynamically incorporate CSS using JavaScript, you can tweak the style of each element along with its corresponding CSS properties. Utilize JavaScript for handling these modifications.

myHtmlElement.style.color='blue';

A similar approach should suffice for your requirements.

Answer №3

Like some have already pointed out, utilizing each element's style property is one approach to take. However, if you're aiming for more generic regulations such as

.customStyle { border-color: myColor }
, you'll need to dynamically create the entire CSS rule:

https://developer.mozilla.org/en/DOM/stylesheet.insertRule

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

What is the best way to implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

Using AJAX for uploading files upon a change event rather than upon submission

Below is the code I have been using to implement an iframe for ajax file upload without refreshing the page upon form submission. The current code works as expected. window.onload=init; function init() { document.getElementById('form').onsubmi ...

Convert an array of objects into an array of objects with combined values

Here is an example of an array containing objects: array = [ {prop1: 'teste1', prop2: 'value1', prop3: 'anotherValue1' }, {prop1: 'teste2', prop2: 'value2', prop3: 'anotherValue2' }, {prop1: &apo ...

What is the best way to center text vertically within an image?

How can I vertically align a blog entry title on an entry thumbnail image? The image size changes with the window size and the title varies in length for each entry. After finding a website that successfully achieved this effect, I tried replicating it us ...

Flexbox: Arrange header and footer in a sidebar layout using flexbox styling

In my content layout, I have structured the sections as header, content, and footer. While I want to maintain this order for small devices, I am looking to shift the header and footer to the sidebar on desktop. I have already implemented this using floats ...

Automatically adapt the height of a bootstrap button based on the dimensions of other bootstrap buttons

First and foremost, my objective is to centrally align a glyphicon both vertically and horizontally within a button. Despite attempting CSS attributes like position: relative; and position: absolute;, my efforts have been in vain. You can check out the sam ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

What is the reason for making the position of bg-container absolute?

Discover more about the "position: absolute" attribute Remove the position property for troubleshooting After testing this page in Chrome, I encountered a confusion regarding the usage of the position property within the bg-container. To my surprise, del ...

Is it possible to view the frames/packets being transmitted from an EJS or HTML form to the Express backend using Express Js?

My current computer science assignment involves visually representing the data transfer process between a frontend and backend. I don't need to show the full data, just the flow of chunks and how it navigates through protocols. Could someone please g ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Steps for positioning an item above CardActionArea

I would like to figure out how to position an object above the CardActionArea. For example, if I have a button on top of the CardActionArea and click on that button, both the CardAction and Button actions will be triggered simultaneously. I want it so that ...

Creating a multi-dimensional array using information from a database

I have a unique challenge where I am utilizing a template that generates a menu with a specific structure. In my database, I have various menus stored and I've successfully retrieved them. However, the issue arises when I need to figure out a way to d ...

[entity: undefined prototype] { type: 'clip', info: 'Watch my latest video!!' } using nodejs - multer

import routes from "./routes"; import multer from "multer"; const multerVideo = multer({ dest: "videos/" }); export const localsMiddleware = (req, res, next) => { res.locals.siteName = "Webtube"; res.locals.routes = routes; res.locals.user = { isA ...

Can someone help me figure out how to make my Dropdown stay open when I highlight input, drag, and release

While working with the react bootstrap Dropdown component, I've encountered a specific behavior that is causing some trouble. To better illustrate the issue, I've attached some images. In my dropdown, there is an input filter box along with a li ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...

An issue arises in Node.js and MongoDB where data is being returned from the previous update instead of the most

Currently, I'm delving into the world of Node.js and creating a platform where individuals can vote on different items and view the results afterward. The voting process involves utilizing the /coffeeorwater POST route, which then redirects to the /re ...

Implementing a codeigniter delete confirmation box with Javascript

I have tried numerous solutions on this site, but nothing seems to be working for me. I am trying to implement a pop-up window confirmation before deleting my data. Here is the code I am using: <a href="<?php echo site_url('admin/barang/delet ...

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

Accessing feedback from Reddit's API

After writing some code to search Reddit's API with a specific query, I now want it to display comments as well. Inside my $.getJSON statement that retrieves each title/post based on the search query, I have the following nested code block. The goal i ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...