Search⌘ K
AI Features

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

Understand how to use JavaScript to add actions to your web page by handling click events and toggling CSS classes. This lesson guides you through a simple function that changes element styles dynamically and introduces the connection between JavaScript and the DOM for interactive web development.


HOW IT WORKS


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

HTML
<!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    value = value === '' ?
...