We use JavaScript to control the behaviour of a web page. We do this by adding events to our page. Examples would be to “listen” for a click or for when the mouse hovers over an image or when the user hits a key on their keyboard etc. The process of events is that we assign an event and then “listen” for a desired response from the user.

To add an event listener we use the addEventListen method which is what we’re going to discuss in more detail in this post and even use them to make a little game. The syntax for the addEventListen is shown below where the type indicates the type of event (click, hover etc) and the function is the code that you want to execute upon the occurrence of the event.

element.addEventListener(type, functionToCall);

An example of a complete event can be seen in the following code. We firstly select the item (in this case a button) using a new variable and then add an event listener that executes when someone clicks a button.

var button = document.querySelector("button");
button.addEventListener("click", function() {
  console.log("SOMEONE CLICKED THE BUTTON!");
});

To implement this into a web page the following will be used in the HTML page.

<button>Click Me</button>
<p class="example">No One Has Clicked Me Yet</p>

This is the code to be used in the JavaScript file.

var button = document.querySelector("button");
var paragraph = document.querySelector("#example");

//SETUP CLICK LISTENER
button.addEventListener("click", function() {
  paragraph.textContent = "Someone Clicked the Button!";
});

The code above will listen out for when a user clicks on the button (in the HTML code) and then change the text using the textContent method (as discussed in the post 4 Areas of DOM Manipulation in JavaScript) indicating the fact that someone has clicked the button.

As part of a coding project I’m working on, I was told that I needed to code a “score keeper” in JavaScript. This is a simple program that would allow two friends to keep track of the scores in a game that they’re playing or whatever. The score keeper software that I made is shown below.


Score Keeper Game (live example)

0 to 0

Playing to: 10

// NOTE: the game isn’t perfect, you can still take the score lower than 0 and carry on to infinity if you lower the winning score threshold while playing but it’s a good illustration of the functionality of the methods being discussed.


When you click on either player 1 or player 2’s buttons the appropriate score will be shown. The score limit can be changed and once a player reaches the score limit, the game is over. The game can be reset at any time which will reset the score limit as well (to the default 10).

There were a number of ways this could have been implemented and the way I did it was slightly different to the methods discussed in the solution in the course but I wanted mine to work slightly different (so I made it that way).

The first thing I did was to select the buttons that increment the players scores so that I could update the text in the h2 tags with each players score using JavaScript. This was done using the document.querySelector method ensuring I use a “#” as I’m using the query selector to find an ID (I’ve included the full HTML element of this program which is shown at the end of this post if you’re looking to see how the information is being found).

var p1Button = document.querySelector("#p1Button");
var p2Button = document.querySelector("#p2Button");

Once the buttons were added an event listener listening for a user click was added once the following required variables were created.

// Initialise score variables
var p1Score = 0
var p2Score = 0
var gameOver = false;
var limit = 10;

The final variables that are needed are the selectors that display the users score (denoted by span tags in the HTML code shown above).

// Next select the span tags so we can update the players score
var p1Display = document.querySelector("#p1Score");
var p2Display = document.querySelector("#p2Score");

These variables were then used to add the event listener to the buttons.

// Add event listner on "click" that changes the score (button 1)
p1Button.addEventListener("click", function() {
	if (!gameOver){
		p1Score += 1;
		p1Display.textContent = p1Score;
		if (p1Score === limit){
			p1Display.classList.add("winner");
			gameOver = true;
		}
	}
});

It basically says: If someone clicks on a button (p1 or p2), if the game isn’t over then increment the score for that player by one. Once the score has been incremented we then perform a check to see if the player has reached the winning Score. If he has then change the class of the h2 tag to “winner” (change it to green) and declare that the game is over (preventing any more scores to be added to the display).

// Add event listner on "click" that changes the score (button 2)
p2Button.addEventListener("click", function() {
	if (!gameOver){
		p2Score += 1;
		p2Display.textContent = p2Score;
		if (p2Score === limit){
			p2Display.classList.add("winner");
			gameOver = true;
		}
	}
});	

The next thing that was done was allowing the user to change the score limit. This time, instead of using a “click” listener, a “change” listener was used which means that the value will be updated as per the value of the text input (regardless of whether it was typed or incremented via clicks).

// Add event listener on "change" that changes the score (button 2)
input.addEventListener("change", function() {
	scoreLimit.textContent = this.value;
	limit = Number(this.value);
});	

// NOTE: “this” as in “this.value” was used instead of “input.value” to illustrate an example of the word “this” in JavaScript.

The next thing (once that was working) was to get the reset button to work. This was done (again) by adding an event listener to the “reset” button and resetting the game when it was pressed.

reset.addEventListener("click", function() {
	resetGame();
});

The resetGame element of the listener was implemented using a function (so it could be used when the player changes the score limit but I kept that out of the game – I wanted to be able to change the score limit in game) as shown below.

function resetGame(){
	p1Score = 0
	p2Score = 0
	p1Display.classList.remove("winner");
	p2Display.classList.remove("winner");
	p1Display.textContent = 0
	p2Display.textContent = 0
	gameOver = false;
	scoreLimit.textContent = "10";
	limit = 10;
	input.value = 10;
}

The final complete JavaScript program that was written is shown below.

// Firstly select the buttons to increment the score
var p1Button = document.querySelector("#p1Button");
var p2Button = document.querySelector("#p2Button");
var reset = document.querySelector("#reset");
var input = document.querySelector("input");
var scoreLimit = document.querySelector("#limit");

// Initialise score variables
var p1Score = 0
var p2Score = 0
var gameOver = false;
var limit = 10;

// Next select the span tags so we can update the players score
var p1Display = document.querySelector("#p1Score");
var p2Display = document.querySelector("#p2Score");

// Add event listener on "click" that changes the score
p1Button.addEventListener("click", function() {
	if (!gameOver){
		p1Score += 1;
		p1Display.textContent = p1Score;
		if (p1Score === limit){
			p1Display.classList.add("winner");
			gameOver = true;
		}
	}
});

// Add event listener on "click" that changes the score
p2Button.addEventListener("click", function() {
	if (!gameOver){
		p2Score += 1;
		p2Display.textContent = p2Score;
		if (p2Score === limit){
			p2Display.classList.add("winner");
			gameOver = true;
		}
	}
});	

// Add event listener on "change" that changes the score
// limit.
input.addEventListener("change", function() {
	scoreLimit.textContent = this.value;
	limit = Number(this.value);
});	

// Add event listener on "click" that resets the game
reset.addEventListener("click", function() {
	resetGame();
});	

// Function to reset game variables
function resetGame(){
	p1Score = 0
	p2Score = 0
	p1Display.classList.remove("winner");
	p2Display.classList.remove("winner");
	p1Display.textContent = 0
	p2Display.textContent = 0
	gameOver = false;
	scoreLimit.textContent = "10";
	limit = 10;
	input.value = 10;
}

The HTML code for the score keeper is as follows:

<!DOCTYPE html>
<html>
<head>
	<title>Score Keeper</title>
</head>
<body>
	<h1>
         <span id="p1Score">0</span> 
         to 
         <span id="p2Score">0</span>
        </h1>
	<p>
         Playing to: 
         <span id="limit">10</span>
        </p>
	<input type="number">
	<button id="p1Button">Player One</button>
	<button id="p2Button">Player Two</button>
	<button id="reset">Reset</button>

	<!-- JavaScript  -->
	<script type="text/javascript" src="scorekeeper.js"></script>
	<!-- End JavaScript  -->
</body>
</html>

The CSS file that changes the colour of the winning result is as follows:

.winner {
	color:green;
}

That’s it for this post. Hope you enjoyed it!

Leave a Comment

Your email address will not be published. Required fields are marked *