CSS/JS : How to Retrieve a numerical value from a CSS property in JS and modify it?



I’ve tried looking around but was not able to find a clear/easy answer.

Let’s say I want to retrieve some value (size) in px for a CSS style sheet like this :

  width: 150px;
  height: 150px;
  background-color: #f00;
  position: absolute;
  left: 0;
  top: 0;

I’ve tried

let block = document.getElementById("block");
const square = window.getComputedStyle(block)
const width = square.getPropertyValue('width');
block.style.width = size.value * width;

But it returns a string. I’d like to modify the value in px dynamically with JS. Is there a better way or should I create a substring, then convert it to a number?

EDIT : I’ve also tried

let width = block.offsetWidth;

But the result on my page is not at all functional.


I found the solution. Declaring the variables before the function but not inside the function did make my result responsive!

I played around with position and scopes of those newly called variables, and I was finally able to make what I want work. I’ll also add some of my code.

Added code :

    size.addEventListener('input', function () {
        block.style.width = size.value * width + 'px';
        block.style.height = size.value * height + 'px';

Initially, I was putting my declaration of my variable

    const width = block.clientWidth;
    const height = block.clientHeight;

Inside of the function. This causes my page not to be really responsive, but caused some "delay" in the adjustments. When I did put these declarations outside of the function, before, it did work properly.

    // This solution works next 3 lines. only setting CONST works. Retrieves number value.
    // let square = block.getBoundingClientRect();
    // const height = square.height;
    // const width = square.width;

    // This solution. Needs to be outside of the function. Works with either let or const
    // let width = block.offsetWidth;
    // let height = block.offsetHeight;

// This way also works, only if outside of the function
    const width = block.clientWidth;
    const height = block.clientHeight;

All of the above works if called before the function but not inside.

Thank you for your help!

Answered By – m3.b

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More