Chapter 14: HTML and JavaScript Integration

14.1 Introduction

JavaScript is a powerful language used to add interactivity, manipulate HTML elements, and handle user events within web pages.

14.2 Embedding JavaScript in HTML

JavaScript can be added to HTML in three ways:

Example of Inline JavaScript:

    <button onclick="alert('Hello, World!')">Click Me</button>
        

Example of Internal JavaScript:

    <script>
        function showMessage() {
            alert("Welcome to JavaScript Integration!");
        }
    </script>

    <button onclick="showMessage()">Click Me</button>
        

Example of External JavaScript:

Save the following in a file named script.js:

    function greetUser() {
        alert("Hello from an external script!");
    }
        

Then, include it in your HTML:

    <script src="script.js"></script>
        

14.3 Manipulating HTML Elements

JavaScript can modify HTML elements using the document object.

Changing Text Content:

    <p id="demo">Original Text</p>
    <button onclick="changeText()">Change Text</button>

    <script>
        function changeText() {
            document.getElementById("demo").innerHTML = "Text Changed!";
        }
    </script>
        

Changing CSS Styles:

    <p id="styledText">Styled Text</p>
    <button onclick="changeStyle()">Change Style</button>

    <script>
        function changeStyle() {
            document.getElementById("styledText").style.color = "red";
        }
    </script>
        

14.4 Handling Events

JavaScript provides event handlers for user interactions like clicks, mouse movements, and form submissions.

Common Events:

Example of an Event Listener:

    <button id="btn">Click Me</button>

    <script>
        document.getElementById("btn").addEventListener("click", function() {
            alert("Button Clicked!");
        });
    </script>
        

14.5 Working with Forms

JavaScript can validate and process forms before submission.

Example of Form Validation:

    <form onsubmit="return validateForm()">
        <label for="name">Name:</label>
        <input type="text" id="name" required>
        <input type="submit" value="Submit">
    </form>

    <script>
        function validateForm() {
            let name = document.getElementById("name").value;
            if (name === "") {
                alert("Name cannot be empty!");
                return false;
            }
            return true;
        }
    </script>
        

14.6 Summary

In this chapter, we covered: