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

Ways to modify the .MuiSelect-nativeInput element within Material-UI

const styles = makeStyles((theme) => ({ root: { margin: "0px 20px" }, textStyle: { fontFamily: "Comfortaa", }, container: {}, textField: { fontFamily: "Comfortaa", }, dropDownFormSize: { width: &qu ...

I've exhausted all my knowledge but still unable to get Tailwind to work

I've been troubleshooting Tailwind for the past 6 hours. Managed to set it up in a simpler Nextjs/React/Typescript project, but struggling to get it working in this larger codebase. I'm sure I'm missing something obvious, but I'm at a ...

What is the best way to extract the geometry information from a gltf object?

I've been using three.js to load a gltf file with the gltfloader, and now I'm trying to create a particle system. However, I'm having trouble getting the geometry object that I need. function initModel() { var planeGeometry = new THREE ...

What could be the reason for the fluctuating HTML output?

Exploring the world of CSS and HTML, I noticed a curious change in the output when text is added inside a div tag. First: div.bar { display: inline-block; width: 20px; height: 75px; /* We'll override height later */ background-co ...

Tips on how to customize an HTML form submission appearance

Take a look at my file upload form below: <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="filetoupload" id="filetoupload" onchange="this.form.submit();"> </form> I am trying to figure out ...

Do global variables in a node.js server apply across the entire server or exclusively to individual sessions or users?

I have a question that may seem basic, so I apologize in advance - are global variables in node.js applicable server-wide or is their scope limited to the session or user? For example, if I create a global boolean variable in a routes.js file to track whet ...

React Material UI Select component is failing to recognize scrolling event

Having some difficulty understanding how to detect a scroll event with a Select component using Material-UI. The Select has MenuProps={...}, and I want to listen for the scroll event inside it. I've tried putting onScroll within MenuProps={...}, but ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

Is it possible to align a clip-path starting from the right edge?

On my webpage, I have a unique hamburger icon that is positioned 2rem away from the right and top edges. I am looking for a convenient way to create a clip path that grows from its center point. Calculating the center point is not difficult but unfortunate ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

Utilizing classes as types in TypeScript

Why is it possible to use a class as a type in TypeScript, like word: Word in the provided code snippet? class Dict { private words: Words = {}; // I am curious about this specific line add(word: Word) { if (!this.words[word.term]) { this.wor ...

Generate Random Quotes - Each new quote should be different from the previous one

As I tackle the FreeCodeCamp 'Random Quote Machine' front end library project using React JSX, everything seemed to be running smoothly except for one major issue - the same quote was often generated two or three times in a row. Obviously, this i ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

Incorporate a personalized style into the wysihtml5 text editor

Is there a way for me to insert a button that applies a custom class of my choice? I haven't been able to find this feature in the documentation, even though it's a commonly requested one. Here's an example of what I'm looking for: If ...

The selected image should change its border color, while clicking on another image within the same div should deselect the previous image

I could really use some assistance! I've been working on Angular8 and I came across an image that shows how all the div elements are being selected when clicking on an image. Instead of just removing the border effect from the previous image, it only ...

Sending back various results in a javascript function

I am attempting to correlate test scores with values from the level array in order to extract selected values into an output array. However, when I execute the following script in the Firebug console, I encounter the error message "TypeError: level is unde ...

Mesh does not display texture in three.js

I've been attempting to add a texture to my sphere mesh using the code snippet below: var loader = new THREE.TextureLoader(); var balltex = loader.load("pic1.jpg"); var ballmat = new THREE.MeshBasicMaterial({ map: balltex }); var ballgeo = new THREE ...

Utilizing jQuery for seamless communication between parent and child iFrame windows

On my webpage, there is an iFrame containing a table where I want to add a click event to the rows. The challenge is retrieving the selected row within the iFrame from the parent window. The goal is to define a class for a clicked table row like this: $( ...

display a loading spinner for number input fields in HTML5

In my HTML5 project, I am currently utilizing a numeric control (input type="number"). The default behavior displays the spinner (up and down arrows) only on hover. Is there a way to make the spinner permanently visible using CSS or another method? ...

I am attempting to display the Δ symbol on my website, however, it is not appearing on the webpage

In my attempt to display my company logo on the website, I encountered an issue where the Δ symbol is not appearing correctly in the browser. strong class="footer-logo">KyΔnsys</strong To address this problem, I have implemented unicode charset=" ...