STUDY/Java Script

[JS] 3 steps of 'Adding Event'

The Simpler 2022. 7. 12. 14:09

Step 1. Find the element.

Step 2. Listen for the event.

Step 3. React that event. (React means showing something, changing color, printing log, etc.)


index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Momentum App </title>
</head>
 
<body>
  <div class="hello">
    <h1>Click me!</h1>
  </div>
  <script src="app.js"></script>
 
</body>
 
</html>
cs

 

 

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const h1 = document.querySelector(".hello:first-child h1");
 
console.log(h1);
console.dir(h1);
 
function handleTitleClick() {
    const currentColor = h1.style.color
    let newColor;
    if (currentColor === "blue") {
        newColor = "tomato"
    } else {
        newColor = "blue";
    }
    h1.style.color = newColor;
}
 
h1.addEventListener("click", handleTitleClick);
 
 
 
 
cs