Alex Gwyn
Alex Gwyn

Reputation: 35

Javascript - changing widths of images

I'm creating a tug of war website as a small project. My problem is that my javascript doesn't seem to want to work.

    <script>
        function randomTeam(){
            var TeamV = Math.floor((Math.random() *2 ) + 1)
            document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
            return TeamV;
        }

        function changeWidth(TeamV){
            var MetreLeftV = document.getElementById('MetreLeft');
            var MetreRightV = document.getElementById('MetreRight');
            if(TeamV == 1){
                MetreLeftV.style.width += '10px';
                MetreRightV.style.width -= '10px';
            }
            else if(TeamV == 2){
                MetreRightV.style.width += '10px';
                MetreLeftV.style.width -= '10px';
            }
        }
    </script>

Basically, when the page is loaded the randomTeam function is called, and when the button is pressed, it increments the size of your teams side, and decrements the side of the enemy's team. The problem is, it doesn't work at all. Could anyone help me see where this is going wrong? Thank you in advance :')

Upvotes: 0

Views: 36

Answers (1)

epascarello
epascarello

Reputation: 207501

You can not just add 10px to the width. Convert the width to a number, add 10, than add px to it.

MetreLeftV.style.width = (parseFloat(MetreLeftV.style.width) + 10) + "px" 

Do the same for the others and you will need a check for negative numbers.

function randomTeam() {
  var TeamV = Math.floor((Math.random() * 2) + 1)
  document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
  return TeamV;
}

function changeWidth(TeamV) {
  var MetreLeftV = document.getElementById('MetreLeft');
  var MetreRightV = document.getElementById('MetreRight');
  console.log(parseFloat(MetreLeftV.style.width) + 10 + 'px')
  if (TeamV == 1) {
    MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) + 10 + 'px';
    MetreRightV.style.width = parseFloat(MetreRightV.style.width) - 10 + 'px';
  } else if (TeamV == 2) {
    MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) - 10 + 'px';
    MetreRightV.style.width = parseFloat(MetreRightV.style.width) + 10 + 'px'
  }
}

window.setInterval( function () {
    var move = randomTeam();
    changeWidth(move);
}, 1000);
#MetreLeft {
  background-color: red
}
#MetreRight {
  background-color: yellow
}
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>

Upvotes: 1

Related Questions