Skip to content
Advertisement

After clicking button, alert is not showing up

I am doing a project on paper-rock-scissor that has UI. So, I have four buttons, Start game, rock, paper and scissor. I want if I click on the Start game button, an alert (“Please choose rock, paper, or scissor”) will pop-up. Right now if I click on the Start game. There’s nothing happening. I have no idea why? Below are my code :

——– HTML code ———

<!DOCTYPE html>

<html lang="en">
    
    <head>
        <meta charset="utf-8">
        <title>Project Rock Paper Scissors</title>
        <script src = "javascript.js"> </script>
    </head>

    <body>
        <div class="btn-group">
            <button id="startgame"> Start game </button>
            <button id="rock"> Rock </button>
            <button id="paper"> Paper </button>
            <button id="scissor"> Scissor </button>
        </div>    
    </body>

</html>

——– Javascript ———-

const startGame = document.querySelector('#startgame');

if (startGame) {
    startGame.addEventListener('click', () => {
        alert("Choose Rock, Paper or Scissor");
    })
}    

const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissor = document.querySelector('#scissor'); 

Advertisement

Answer

In your code, startGame is returning null

Method 1

In your html code, call javascript code at the end, before closing <body> tag

<!DOCTYPE html>

<html lang="en">
    
    <head>
        <meta charset="utf-8">
        <title>Project Rock Paper Scissors</title>
    </head>

    <body>
        <div class="btn-group">
            <button id="startgame"> Start game </button>
            <button id="rock"> Rock </button>
            <button id="paper"> Paper </button>
            <button id="scissor"> Scissor </button>
        </div>    

        <script src = "javascript.js"> </script>
    </body>

</html>

Method 2

Add the defer attribute to your script tag

<!DOCTYPE html>

<html lang="en">
    
    <head>
        <meta charset="utf-8">
        <title>Project Rock Paper Scissors</title>
        <script src = "javascript.js" defer> </script>
    </head>

    <body>
        <div class="btn-group">
            <button id="startgame"> Start game </button>
            <button id="rock"> Rock </button>
            <button id="paper"> Paper </button>
            <button id="scissor"> Scissor </button>
        </div>    
    </body>

</html>

You can look into this question for more information

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement