Skip to content
Advertisement

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 :

#block{
  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.

Advertisement

Answer

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!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement