1

I am trying to move my robot to the right by toggling between two classes, but it doesn't seem to be working. Please help. Created two classes and was trying to switch between two of those classes with toggle but not working.

function moveR() {
  let robot = document.getElementsByClassName("robot1");
  robot.classList.toggle = "moveRight";
}
.robot1 {
  position: absolute;
  width: 50px;
  height: 50px;
}

#moveRightBtn {
  position: absolute;
  top: 300px;
  font-size: 20px
}

.moveRight {
  animation-name: moveRight;
  animation-duration: 3s;
}

@keyframes moveRight {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100px);
  }
}
<h1 id="Header1">Keyframe Practice</h1>
<h2>Moving The Robot To Right</h2>

<img class="robot1" src="https://cdn-icons.flaticon.com/png/512/630/premium/630426.png? 
        token=exp=1636183057~hmac=45b700055844fa031977edfa2ee4457b">

<button onclick="moveR()" id="moveRightBtn">Move Right</button>
Balastrong
  • 4,336
  • 2
  • 12
  • 31

1 Answers1

1

Solution

Your code has two major problems.

  1. getElementsByClassName returns an array. You just want the first element. An alternative method is by using querySelector(".robot1") that returns the first match.
  2. classList.toggle is a function, you don't have to assign (with =) the class, but pass it as parameter.

These the two changed lines in your code, everything else is fine:

  let robot = document.querySelector(".robot1");
  robot.classList.toggle("moveRight");

Working Demo

function moveR() {
  let robot = document.querySelector(".robot1");
  robot.classList.toggle("moveRight");
}
.robot1 {
  position: absolute;
  width: 50px;
  height: 50px;
}

#moveRightBtn {
  position: absolute;
  top: 300px;
  font-size: 20px
}

.moveRight {
  animation-name: moveRight;
  animation-duration: 3s;
}

@keyframes moveRight {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100px);
  }
}
<h1 id="Header1">Keyframe Practice</h1>
<h2>Moving The Robot To Right</h2>

<img class="robot1" src="https://cdn-icons.flaticon.com/png/512/630/premium/630426.png? 
        token=exp=1636183057~hmac=45b700055844fa031977edfa2ee4457b">

<button onclick="moveR()" id="moveRightBtn">Move Right</button>
Balastrong
  • 4,336
  • 2
  • 12
  • 31