0

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'); 
Masoud
  • 375
  • 1
  • 5
  • 16
Jabri Juhinin
  • 47
  • 1
  • 7

1 Answers1

4

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. Credit-Question asker and some answerers. Parts of this answer may have been inspired from them.

Anonymous
  • 835
  • 1
  • 5
  • 21
  • 1
    This works, thank you so much ! I learned about the 'defer' previously but only now I am facing the real problem. Thanks – Jabri Juhinin Jul 23 '22 at 03:49