Search code examples
javascriptgetelementbyid

Animating brooms


In Javascript, when I click on the broom, it changes the image src to a gif and changes the ID to "walkingBroom". This works.

Then, when I click on the broom, it changes the class (this makes it walks across the screen). This does not work.

I don't know what I doing wrong - can anyone help? It's like the ID has not been changed.

document.getElementById("stillBroom").addEventListener("dblclick", animate);

function animate(){
  document.getElementById("stillBroom").src = "broom.gif";
  document.getElementById("stillBroom").id = "walkingBroom";}


document.getElementById("walkingBroom").addEventListener("click", walk);

function walk(){
  document.getElementById("walkingBroom").className = "broom pattern0 speed1";}

Solution

  • You should manage the logic in a variable, like let currentState="still", then on click, change to currentState="walking", and act in consequence. Currently, you are immediately trying to attach a click event to a "walkingBroom" element that doesn't exist (it will exist, but later, after you click the broom once). For that matter, your console is very likely saying Error - Can't read property addEventListener of null and your script crashes without running. Open your console, it's very useful.

    let currentState = "still";
    broom.addEventListener("dblclick", clickHandler);
    
    const clickHandler = () => {
         switch(currentState) {
              case "still" :
                   currentState="walking";
                   broom.src="broom.gif";
                   break;
              case "walking":
                   currentState="flying";
                   broom.className = "broom pattern0 speed1";
                   break;
         }
    }