skip to Main Content

While I was making stopwatch webpage, I added some JavaScript code for functional buttons. I expected that when I click "Play" button, the text of the button should change to "Pause", but when I clicked it, it doesn’t work. I’m using Tailwind CSS with Vanilla JavaScript as practice to get used to JavaScript before using React, so it is possible that Tailwind CSS might have conflicted with the JavaScript.

HTML (with Tailwind CSS)

<div class="absolute top-[250px] left-[600px]">
    <div class="text-center">
        <h1 class="text-7xl font-bold text-[#f2f2f2]">00:00:00</h1>
    </div>
    <div class="flex justify-center pt-4">
        <button
          type="button"
          class="bg-[#80a5fc] hover:bg-[#6a89d2] w-24 h-16 mx-2 rounded-lg play"
        >
          Play
        </button>
        <button
          type="button"
          class="bg-[#80a5fc] hover:bg-[#6a89d2] w-24 h-16 mx-2 rounded-lg reset"
        >
          Reset
        </button>
        <button
          type="button"
          class="bg-[#80a5fc] hover:bg-[#6a89d2] w-24 h-16 mx-2 rounded-lg lap"
        >
          Lap
        </button>
     </div>
</div>

JavaScript:

const playButton = document.getElementsByClassName("play")[0]
const resetButton = document.getElementsByClassName("reset")[0]
const lapButton = document.getElementsByClassName("lap")[0]

let isPlay = false

const play = () => {
    if (!isPlay) {
        playButton.innerHTML("Pause")
        isPlay = true
    }
    else {
        playButton.innerHTML("Play")
        isPlay = false
    }
}

playButton.addEventListener("click", play)

2

Answers


  1. The innerHTML property is not a function,

    const playButton = document.getElementsByClassName("play")[0];
    
    let isPlay = false;
    
    const play = () => {
        if (!isPlay) {
            playButton.innerHTML = "Pause";
            isPlay = true;
        } else {
            playButton.innerHTML = "Play";
            isPlay = false;
        }
    };
    
    playButton.addEventListener("click", play);
    Login or Signup to reply.
  2. As David mentioned, innerHTML is not a function. Check the console in the fiddle here: https://jsfiddle.net/sc0gbaqn/

    Here’s what you meant to do:

    const play = () => {
            if (!isPlay) {
                playButton.innerHTML = "Pause";
                isPlay = true
            }
            else {
                playButton.innerHTML = "Play";
                isPlay = false
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search