Home > OS >  change css class property increment
change css class property increment

Time:04-12

I have a small question! I'am trying to change css width property using JavaScript like this:

document.getElementById("progressvalue").style.width = "80%";
.progress {
  width: 100%;
  max-width: 500px;
  border: 3px solid black;
  height: 20px;
  padding: 1px;
}

#progressvalue {
  height: 100%;
  width: 0%;
  background-color: #05e35e;
}
<div > 
  <div id="progressvalue"></div>
</div>

But instead of 80% in JavaScript code, I want to increase the width value by 20%. Like (width = width 20%) i want to apply this changing multiple times, and this is why I need it like this (width = width 20%)

CodePudding user response:

You can try it

//offsetWidth : returns the width of the element
var element_width=document.getElementById('progressvalue').offsetWidth

document.getElementById("progressvalue").style.width =element_width   (20*element_width/100) ;

CodePudding user response:

I guess you want to do some animation right ? If so you can use recursivity with setTimeout:

function progress(val) {
    val  = 20;

    document.getElementById("progressvalue").style.width = val   "%";
    if (val < 100) // To stop the loop when progress bar is full
        setTimeout(function () {
            progress(val);
        }, 1000)
}
progress(0); // Start the animation

CodePudding user response:

This will increase by 20% every 0.5 seconds.

let percent = 0;

setInterval(() => 
{
    if(percent > 100) {
        clearInterval();
        return;
    }
    document.getElementById("progressvalue").style.width = percent   "%";
    percent  = 20;
}, 500);

CodePudding user response:

You can use this:

    var el = document.getElementById("progressvalue");

    var elementWidth = el.style.width;

    var newWidth = `${20 parseInt(elementWidth.substring(0, elementWidth.length-1))}%`
    el.style.width=newWidth;

Assuming that you have set the width of the element initially to a percent value.

  • Related