HTML – Using JavaScript

Introduction

In this chapter, you will learn about incorporating JavaScript into HTML to add interactivity and dynamic behavior to your web pages. JavaScript is a powerful scripting language that runs in the browser, allowing you to manipulate HTML elements, handle events, and perform various other tasks.

Adding JavaScript to HTML

There are several ways to include JavaScript in your HTML documents: inline JavaScript, internal JavaScript, and external JavaScript.

Inline JavaScript

Inline JavaScript is added directly within an HTML element using the onclick, onmouseover, or other event attributes.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inline JavaScript Example</title>
</head>
<body>
    <h1>Inline JavaScript Example</h1>
    <button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>

Explanation

In this example, the onclick attribute in the <button> tag contains a JavaScript alert function. When the button is clicked, an alert box with the message "Button clicked!" appears.

Internal JavaScript

Internal JavaScript is written within a <script> tag inside the <head> or <body> section of the HTML document.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal JavaScript Example</title>
    <script>
        function showAlert() {
            alert('Button clicked!');
        }
    </script>
</head>
<body>
    <h1>Internal JavaScript Example</h1>
    <button onclick="showAlert()">Click Me</button>
</body>
</html>

Explanation

In this example, a JavaScript function showAlert is defined within a <script> tag. The button’s onclick attribute calls this function when clicked, displaying an alert box with the message "Button clicked!".

External JavaScript

External JavaScript is written in a separate file with a .js extension and linked to the HTML document using the <script> tag with the src attribute.

Example

HTML Document

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External JavaScript Example</title>
    <script src="script.js"></script>
</head>
<body>
    <h1>External JavaScript Example</h1>
    <button onclick="showAlert()">Click Me</button>
</body>
</html>

External JavaScript File (script.js)

function showAlert() {
    alert('Button clicked!');
}

Explanation

In this example, the JavaScript function showAlert is defined in an external file script.js. The HTML document includes this script file using the <script src="script.js"></script> tag. The button calls the showAlert function when clicked, displaying an alert box with the message "Button clicked!".

JavaScript Basics

Variables

Variables are used to store data values. You can declare variables using var, let, or const.

Example

var name = 'John';
let age = 30;
const isStudent = true;

Explanation

In this example, three variables are declared: name with the value 'John', age with the value 30, and isStudent with the value true. The var, let, and const keywords are used to declare variables with different scopes.

Functions

Functions are blocks of code designed to perform a particular task. They are executed when called.

Example

function greet() {
    alert('Hello, World!');
}

greet(); // Calling the function

Explanation

In this example, a function greet is defined, which displays an alert box with the message "Hello, World!" when called. The function is then called using greet().

Events

Events are actions that occur in the browser, such as clicking a button or loading a page. You can write JavaScript to respond to these events.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Events Example</title>
    <script>
        function changeText() {
            document.getElementById('text').innerHTML = 'Text changed!';
        }
    </script>
</head>
<body>
    <h1>JavaScript Events Example</h1>
    <p id="text">Original text.</p>
    <button onclick="changeText()">Change Text</button>
</body>
</html>

Explanation

In this example, a function changeText is defined to change the inner HTML of a paragraph with the ID text. When the button is clicked, the changeText function is called, updating the paragraph text to "Text changed!".

DOM Manipulation

The Document Object Model (DOM) represents the structure of an HTML document. JavaScript can be used to manipulate the DOM, allowing you to change the content and style of your web pages dynamically.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Manipulation Example</title>
    <script>
        function changeStyle() {
            document.getElementById('text').style.color = 'red';
            document.getElementById('text').style.fontSize = '20px';
        }
    </script>
</head>
<body>
    <h1>DOM Manipulation Example</h1>
    <p id="text">This text will change style.</p>
    <button onclick="changeStyle()">Change Style</button>
</body>
</html>

Explanation

In this example, a function changeStyle is defined to change the color and font size of a paragraph with the ID text. When the button is clicked, the changeStyle function is called, updating the paragraph’s style properties.

Real-World Use Case: Simple To-Do List

A common use case for JavaScript is creating a simple to-do list application that allows users to add and remove tasks.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple To-Do List</title>
    <style>
        .task {
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
        }
        .task button {
            background: red;
            color: white;
            border: none;
            cursor: pointer;
        }
    </style>
    <script>
        function addTask() {
            const taskText = document.getElementById('task-input').value;
            if (taskText === '') return;

            const taskList = document.getElementById('task-list');
            const taskItem = document.createElement('div');
            taskItem.className = 'task';
            taskItem.innerHTML = `${taskText} <button onclick="removeTask(this)">Remove</button>`;

            taskList.appendChild(taskItem);
            document.getElementById('task-input').value = '';
        }

        function removeTask(button) {
            const taskItem = button.parentNode;
            taskItem.remove();
        }
    </script>
</head>
<body>
    <h1>Simple To-Do List</h1>
    <input type="text" id="task-input" placeholder="Enter a new task">
    <button onclick="addTask()">Add Task</button>
    <div id="task-list"></div>
</body>
</html>

Explanation

In this example, a simple to-do list application is created using JavaScript. The addTask function adds a new task to the list when the "Add Task" button is clicked. Each task has a "Remove" button, which calls the removeTask function to remove the task from the list.

Conclusion

JavaScript is a powerful language for adding interactivity and dynamic behavior to your HTML pages. By using inline, internal, or external JavaScript, you can create interactive web experiences. Understanding JavaScript basics, events, and DOM manipulation is essential for modern web development. The real-world example of a simple to-do list demonstrates how JavaScript can be used to create useful and interactive applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top