'how do I add width values to increase by x amount?
I'm making an EFPS bar for games, and ive got JS code to get the ID of the element. This works perfect, but how do I get it to add 30% to the already existing width percent of the bar? The width it's set to by default is 18. So it should change to 48% but it replaces it with 30%. I have tried using += but that just makes it not work.
document.getElementById("mwfps").style.width = "30%";
Solution 1:[1]
Try this:
const obj = document.getElementById("mwfps");
obj.style.width = `${Number(obj.style.width)+30}%`
Solution 2:[2]
First you need to set the width as inline style if you want to retrieve the percentage value otherwise you will always get the pixel transformed values and you will have to make the conversion with some math.
Then you can retrieve the width from style object, get rid of % symbol, perform the sum, and return a new percentage.
select.onchange = e => {
const width = mwfps.style.width
mwfps.style.width = +width.replace("%", "") + +e.target.value + "%"
const newWidth = mwfps.style.width
mwfps.innerText = newWidth
}
#mwfps {
background: orange;
height: 20px;
}
<div id="mwfps" style="width:18%">18%</div>
<select id="select">
<option value="10">10%</option>
<option value="20">20%</option>
<option value="30">30%</option>
<option value="40">40%</option>
</select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Imran Rafiq Rather |
| Solution 2 |
