1

its my code and I wanna decrease width of div any time click on button with random number

let humanDiv = document.getElementById("humanDiv");
let monsterDiv = document.getElementById("monsterDiv");

function attBtn() {
let numRandom = Math.floor(Math.random() * 40) + 1;
humanDiv.style.width -= numRandom + 'px';
monsterDiv.style.width -= numRandom + 'px';
}
ATP
  • 2,939
  • 4
  • 13
  • 34

3 Answers3

1

object.style.width gives you a string you can't use -= on it.

Try :

humanDiv.style.width = parseInt(humanDiv.style.width)+ numRandom + 'px';
monsterDiv.style.width = parseInt(monsterDiv.style.width) + numRandom + 'px';
Krystian
  • 122
  • 1
  • 10
ATP
  • 2,939
  • 4
  • 13
  • 34
0

The width of an element can't be accessed when it wasn't set previously:

 console.log(humanDiv.style.width);

// will give 
//
// (nothing)

So it doesn't make sense to subtract nothing by a random number.

CSS transform might help you: CSS Transform with element resizing.

Krystian
  • 122
  • 1
  • 10
MoPaMo
  • 517
  • 6
  • 24
0

humanDiv.style.width properties returns string with the pixels in the end so before decreasing it you should convert this property into the number.

<script>
  let humanDiv = document.getElementById("humanDiv");
  let monsterDiv = document.getElementById("monsterDiv");

  function attBtn() {
    let numRandom = Math.floor(Math.random() * 40) + 1;
    let humanDivWidth = new Number(humanDiv.style.width.slice(0, -2));
    let monsterDivWidth = new Number(humanDiv.style.width.slice(0, -2));
    humanDiv.style.width = humanDivWidth - numRandom + "px";
    monsterDiv.style.width = monsterDivWidth - numRandom + "px";
  }
</script>
laurisstepanovs
  • 432
  • 5
  • 14