Skip to content

Commit 2bbf7f9

Browse files
committed
32 Adding, Removing & Toggling HTML Classes on Elements | README's Index not completely updated (links not working)
1 parent 28445b6 commit 2bbf7f9

4 files changed

Lines changed: 97 additions & 92 deletions

File tree

JS-DOM/index.html

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
</head>
1515

1616
<body>
17+
<div class="info">
18+
<h1>The Pig Game</h1>
19+
<a href="#" id="rules">&lt;Rules of the Game&gt;</a>
20+
</div>
1721
<div class="wrapper clearfix">
1822
<div class="player-0-panel active">
1923
<div class="player-name" id="name-0">Player 1</div>

JS-DOM/scripts/app.js

Lines changed: 77 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,25 @@
1-
21
/* The Pig Game
32
GAME RULES:
43
54
- The game has 2 players, playing in rounds
6-
- In each turn, a player rolls a dice as many times as he whishes. Each result get added to his ROUND score
7-
- BUT, if the player rolls a 1, all his ROUND score gets lost. After that, it's the next player's turn
8-
- The player can choose to 'Hold', which means that his ROUND score gets added to his GLBAL score. After that, it's the next player's turn
5+
- In each turn, a player rolls a dice as many times as he whishes. Each result get added to
6+
his ROUND score
7+
- BUT, if the player rolls a 1, all his ROUND score gets lost. After that, it's the next
8+
player's turn
9+
- The player can choose to 'Hold', which means that his ROUND score gets added to his GLOBAL
10+
score. After that, it's the next player's turn
911
- The first player to reach 100 points on GLOBAL score wins the game
1012
1113
*/
1214

13-
/********************************************************************************************
14-
* Events: Notifications that are sent to notify the JS code that something has happened
15-
* on the Webpage. Ex: Clicking a button, resizing a window, scrolling down or
16-
* pressing a key.
17-
*
18-
* Event Listener: A function that performs an action based on a certain event. It waits for
19-
* a specific event to happen in the browser.
20-
*
21-
* Q) How are events processed?
22-
* A) The rule is that, for an even to be processed, all the functions that are in the
23-
* stack i.e., all the execution stacks have to be processed first, and then, any event
24-
* can be processed on top of the Global Execution Stack. All the events wait inside
25-
* the Message Queue. From the message queue, the events are executed in FIFO order.
26-
* For every event, there's an evenet listener which is the event handler which calls
27-
* a function and an execution context for that event handler is pushed on top of the
28-
* execution stack.
29-
*/
30-
31-
3215
/********************************************************************************************
3316
* What we'll learn:
34-
* 1. How to setup an event handler
35-
* 2. What a callback function is
36-
* 3. What an anonymous function is
37-
* 4. Another way to select elements by ID
38-
* 5. How to change the image in an <img> element
17+
* 1. How to use ternary operators
18+
* 2. How to add, remove & toggle HTML classes for an element
3919
*/
4020

41-
//var scores = [0, 0];
42-
//var roundScore = 0;
43-
//var activePlayer = 0; // 0 => Player-1; 1 => Player-2
44-
//var dice = Math.floor(Math.random() * 6) + 1;
45-
//console.log(dice); // Testing the dice functionality.
46-
//document.querySelector("#score-0").textContent = dice;
47-
//document.querySelector("#current-0").textContent = dice;
48-
//activePlayer = 1;
49-
//document.querySelector("#score-" + activePlayer).textContent = dice;
50-
//document.querySelector("#current-" + activePlayer).innerHTML = "<em>" + dice + "</em>";
51-
//document.querySelector("#score-" + activePlayer).textContent = "<em>" + dice + "</em>";
52-
//var dom = document.querySelector("#score-0").textContent;
53-
//console.log(dom);
54-
//document.querySelector(".dice").style.display = "none";
55-
56-
5721
// We generally write variable declarations on top for a small project, so that the code
5822
// seems uniform and simple to navigate.
59-
6023
var scores, roundScore, activePlayer;
6124
scores = [0,0];
6225
roundScore = 0;
@@ -65,63 +28,86 @@ activePlayer = 0; // 0 => Player-1; 1 => Player-2
6528
// Hide the dice image when opening the page for the first time
6629
document.querySelector('.dice').style.display = "none";
6730

68-
/* Adding an Event Listener */
69-
// Add functionality to wiht "Roll Dice" which has the .btn-roll class.
70-
// We use addEventListener(<event_type>, <event_handler>)
71-
72-
// The <event_type> is a string that is an event. To get a click on the button, we send
73-
// the 'click' event as the <event_type>. For more event definitions, follow this link:
74-
// https://developer.mozilla.org/en-US/docs/Web/Events
75-
76-
// <event_handler> is a parameter that takes a function. The addEventListener() takes in
77-
// a string (which is <event_type>) & a function (which is <event_handler>).
78-
// This function can be passed in 2 different ways (we'll understand this later).
79-
// The function that's passed, will be called by the addEventListener() method, whenever
80-
// the event is actually triggered in the webpage by the user/browser, and thereby,
81-
// the function is called. Therefore, in this case, addEventListener() is a function, that
82-
// takes in a function, and calls that function (which is the <event_handler>) only when
83-
// the event to that related function happens, this makes the addEventListener() method,
84-
// a callback method/function. A function which call another function due to certain
85-
// events, is known as a Callback function.
86-
87-
// There are 2 different ways to send the function as a parameter in JS.
88-
// Way #1: Define the function using function expression & send the variable associated
89-
// to that function as the <event_handler> to addEventListener() method i.e.,
90-
// var btn_roll = function() {
91-
// // Do Something to Handle the Event
92-
// };
93-
// document.querySelector(".btn-roll").addEventListener('click', btn_roll);
94-
95-
// Way #2: Define the function in the <event_handler>'s parameter, as an anonyous function
96-
// as follows:
97-
98-
// The <event_handler> to the addEventListener() method in line 100, is defined when passing
99-
// and also, that function has no name, and therefore, such functions are known to be
100-
// Anonymous Functions.
31+
document.getElementById("score-0").textContent = "0"; // Set Initial Score for Player 1 = 0
32+
document.getElementById("score-1").textContent = "0"; // Set Initial Score for Player 2 = 0
33+
document.getElementById("current-0").textContent = "0"; //Init Overall Score for Player 1 = 0
34+
document.getElementById("current-1").textContent = "0"; //Init Overall Score for Player 2 = 0
10135

36+
// Event Handler for Rolling the Dice
10237
document.querySelector(".btn-roll").addEventListener("click", function() {
10338
// 1. Generate a Random Number for the dice:
10439
var dice = Math.floor(Math.random() * 6) + 1;
10540

10641
// 2. Display the Result
10742
var diceDOM = document.querySelector(".dice");
43+
10844
// Since the diceDOM is an <img> element, we can access its src attribute as a property
10945
diceDOM.src = "./img/dice-" + dice + ".png";
11046
diceDOM.style.display = "block";
11147

11248
// 3. Update the roundScore iff dice !== 1
49+
if(dice !== 1) { // When we don't roll a 1
50+
51+
/* Add the score generated by the dice to the roundScore: */
52+
roundScore += dice;
53+
54+
/* Display the roundScore to the current activePlayer's temporary score holder */
55+
document.getElementById("current-" + activePlayer).textContent = roundScore;
56+
57+
} else { // When we roll a 1
58+
59+
/* Change the activePlayer using the ternary operator */
60+
activePlayer = activePlayer === 0 ? 1 : 0;
61+
62+
/* Reset the roundScore to 0 */
63+
roundScore = 0;
64+
65+
/* Set the current scores of both Players (P1 & P2) to 0 */
66+
document.getElementById("current-0").textContent = 0;
67+
document.getElementById("current-1").textContent = 0;
68+
69+
/**
70+
* Apply the active class to emphasize the current player who has the current turn
71+
* to throw the die using the classList property as follows:
72+
*/
73+
// if (activePlayer === 0) { // P1's turn
74+
// document.querySelector(".player-1-panel").classList.remove("active");
75+
// document.querySelector(".player-0-panel").classList.add("active");
76+
// } else {
77+
// document.querySelector(".player-1-panel").classList.add("active");
78+
// document.querySelector(".player-0-panel").classList.remove("active");
79+
// }
80+
/**
81+
* The code above is too big and tedious. Instead, we just use a single toggle()
82+
* method in the classList property as follows:
83+
*/
84+
document.querySelector(".player-1-panel").classList.toggle("active");
85+
document.querySelector(".player-0-panel").classList.toggle("active");
86+
/**
87+
* toggle() method will remove the .active class from the intended element, if it
88+
* was applied to the element before, and it will apply the .active class to the
89+
* intended element if it was not applied to the intended element.
90+
*/
91+
92+
/* Hide the dice image when we roll a 1 */
93+
document.querySelector(".dice").style.display = "none";
94+
}
11395
});
11496

115-
// We can select the HTML elements using the querySelector() method, or the other methods
116-
// like getElementById(), getElementsByClassName(), getElementsByName(),
117-
// getElementsByTagName(), etc. getElementById() & querySelector() methods are used to select
118-
// a single element and do something with it. But using getElementsByClass(),
119-
// getElementsByName(), getElementsByTagName(), etc, we select multiple elements at once.
120-
121-
// Example of getElementById():
122-
// (We can only select elements which have id's with this method)
123-
document.getElementById("score-0").textContent = "0"; // Set Initial Score for Player 1 = 0
124-
document.getElementById("score-1").textContent = "0"; // Set Initial Score for Player 2 = 0
125-
document.getElementById("current-0").textContent = "0"; //Init Overall Score for Player 1 = 0
126-
document.getElementById("current-1").textContent = "0"; //Init Overall Score for Player 2 = 0
127-
97+
// Event Handler for Showing the Rules
98+
document.querySelector("#rules").addEventListener('click', function() {
99+
var rule = [];
100+
rule[0] = "The game has 2 players, playing in rounds (By default, Player 1 starts)";
101+
rule[1] = "In each turn, a player rolls a dice as many times as s/he wishes. Each die roll's result gets added to their ROUND score";
102+
rule[2] = "BUT, if the player rolls a 1, entire ROUND score accumulated till now, becomes 0. After that, it's the next player's turn";
103+
rule[3] = "The player can choose to 'Hold', which means that the current player's ROUND score gets added to their GLOBAL score. After that, it's the next player's turn";
104+
rule[4] = "The first player to reach 100 points on GLOBAL score wins the game";
105+
106+
var showAlert = function(messageList) {
107+
var messageString = "";
108+
for(var i = 0; i < messageList.length; ++i)
109+
messageString += (i + 1) + ". " + messageList[i] + ".\n";
110+
alert(messageString);
111+
}
112+
showAlert(rule);
113+
});

JS-DOM/styles/style.css

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,20 @@ body {
2626
color: #555;
2727
}
2828

29+
.info {
30+
text-align: center;
31+
color: #fff;
32+
}
33+
34+
.info h1 {
35+
font-weight: 600;
36+
letter-spacing: 1vh;
37+
}
38+
39+
.info a { text-decoration: none; }
40+
.info a:hover { text-decoration: underline; }
41+
.info a:visited { color: antiquewhite; }
42+
2943
.wrapper {
3044
width: 1000px;
3145
position: absolute;

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,5 @@ Syntax -
5050
3. <strong>JS DOM: The Pig Game</strong>
5151
(Common Markup: [index.html](https://github.com/Ch-sriram/JavaScript/blob/master/JS-DOM/index.html))
5252
1. DOM Access & Manipulation: [Pig Game (Version 1)](https://github.com/Ch-sriram/JavaScript/blob/1b504a0df042ceb2a74401975c08b5f0c97e146e/JS-DOM/scripts/app.js)
53-
2. Events & Event Handling: [Pig Game (Version 2)](https://github.com/Ch-sriram/JavaScript/blob/8b0249a1d8105294f79f9c1042a54253484aaf5e/JS-DOM/scripts/app.js)
53+
2. Events & Event Handling: [Pig Game (Version 2)](https://github.com/Ch-sriram/JavaScript/blob/8b0249a1d8105294f79f9c1042a54253484aaf5e/JS-DOM/scripts/app.js)
54+
3. Adding, Removing & Toggling HTML Classes: [Pig Game (Version 3)]()

0 commit comments

Comments
 (0)