JavaScript - DOM and Events Fundamentals

Last Updated on: August 10, 2021 pm

DOM and Events Fundamentals

DOM !== JS

DOM Methods and Properties for DOM Manipulations ARE NOT PART OF JavaScript!

WEB APIs can INTERACT WITH JS!

Guess My Number Project

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
let number = Math.trunc(Math.random() * 20 + 1); // state variable
let score = 20; // state variable
let highscore = 0;

const displayMsg = function (msg) {
document.querySelector('.message').textContent = msg;
};

document.querySelector('.again').addEventListener('click', () => {
score = 20;
document.querySelector('.score').textContent = score;
displayMsg('Start guessing...');
number = Math.trunc(Math.random() * 20 + 1);
document.querySelector('.number').textContent = '?';
document.querySelector('.guess').value = '';
document.querySelector('body').style.backgroundColor = '#222';
document.querySelector('.number').style.width = '15rem';
});

document.querySelector('.check').addEventListener('click', () => {
const guess = Number(document.querySelector('.guess').value);
console.log(guess);
if (!guess) {
displayMsg('No Number! 🚫 ');
} else if (guess === number) {
displayMsg('Correct Number!!');
document.querySelector('.number').textContent = number;
document.querySelector('body').style.backgroundColor = '#60b347';
document.querySelector('.number').style.width = '30rem';
if (score > highscore) {
highscore = score;
document.querySelector('.highscore').textContent = highscore;
}
} else if (guess !== number) {
if (score > 1) {
document.querySelector('.message').textContent =
guess > number ? 'Your guess is larger!! ' : 'Your guess is smaller!!';
score--;
document.querySelector('.score').textContent = score;
} else {
displayMsg(' 💥 You are losing!!');
}
}
});

Open and Close Modal Functions

1
2
3
4
5
6
7
8
9
const openModal = function () {
console.log('Button Clicked!!');
modal.classList.remove('hidden'); // no dot for class name
overlay.classList.remove('hidden');
};
const closeModal = function () {
modal.classList.add('hidden');
overlay.classList.add('hidden');
};

Handle Key Press Events

Hide the modal if Esc key is pressed.

1
2
3
4
5
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
closeModal();
}
});

Practice Project - Pig Game

Flow Chart