...

/

How It Works: Adding Actions to the Web Page with JS

How It Works: Adding Actions to the Web Page with JS

In this lesson, we'll understand the workings of the previous lesson's exercise. Let's begin!


HOW IT WORKS


The key to this behavior is the handleClick function you added to index.html in step 3.

<!DOCTYPE html>
<html>
<head>
<title>Table of Contents</title>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<h1 onclick="handleClick(this)">
Introduction
</h1>
<h2>Whom this book is for?</h2>
<h2>Errata</h2>
<h1 onclick="handleClick(this)">
Chapter 1
</h1>
<h2>What you will learn in this chapter</h2>
<h2>Summary</h2>
<h1 onclick="handleClick(this)">
Chapter 2
</h1>
<h2>Recap</h2>
<h2>Conclusion</h2>
<script>
function handleClick(node) {
var value = node.getAttribute('class') || '';
value = value === '' ? 'clicked' : '';
node.setAttribute('class', value);
}
</script>
</body>
</html>

When loading a page, the browser recognizes the <script> sections and immediately executes the code within. Here, the <script> contains a function definition and executing the code means that the definition is hoisted into the current page’s JavaScript context. Let’s have a look at what this function does.

1  function handleClick(node) {
2    var value = node.getAttribute('class') || '';
3   
...
Access this course and 1400+ top-rated courses and projects.