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 ———
JavaScript
x
21
21
1
<!DOCTYPE html>
2
3
<html lang="en">
4
5
<head>
6
<meta charset="utf-8">
7
<title>Project Rock Paper Scissors</title>
8
<script src = "javascript.js"> </script>
9
</head>
10
11
<body>
12
<div class="btn-group">
13
<button id="startgame"> Start game </button>
14
<button id="rock"> Rock </button>
15
<button id="paper"> Paper </button>
16
<button id="scissor"> Scissor </button>
17
</div>
18
</body>
19
20
</html>
21
——– Javascript ———-
JavaScript
1
12
12
1
const startGame = document.querySelector('#startgame');
2
3
if (startGame) {
4
startGame.addEventListener('click', () => {
5
alert("Choose Rock, Paper or Scissor");
6
})
7
}
8
9
const rock = document.querySelector('#rock');
10
const paper = document.querySelector('#paper');
11
const scissor = document.querySelector('#scissor');
12
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
JavaScript
1
22
22
1
<!DOCTYPE html>
2
3
<html lang="en">
4
5
<head>
6
<meta charset="utf-8">
7
<title>Project Rock Paper Scissors</title>
8
</head>
9
10
<body>
11
<div class="btn-group">
12
<button id="startgame"> Start game </button>
13
<button id="rock"> Rock </button>
14
<button id="paper"> Paper </button>
15
<button id="scissor"> Scissor </button>
16
</div>
17
18
<script src = "javascript.js"> </script>
19
</body>
20
21
</html>
22
Method 2
Add the defer attribute to your script tag
JavaScript
1
21
21
1
<!DOCTYPE html>
2
3
<html lang="en">
4
5
<head>
6
<meta charset="utf-8">
7
<title>Project Rock Paper Scissors</title>
8
<script src = "javascript.js" defer> </script>
9
</head>
10
11
<body>
12
<div class="btn-group">
13
<button id="startgame"> Start game </button>
14
<button id="rock"> Rock </button>
15
<button id="paper"> Paper </button>
16
<button id="scissor"> Scissor </button>
17
</div>
18
</body>
19
20
</html>
21
You can look into this question for more information