HTML and JavaScript

JavaScript is a powerful programming language that brings interactivity and dynamic functionality to HTML webpages. By combining HTML, CSS, and JavaScript, we can create responsive and engaging websites.

In this chapter, we will explore:

  1. Adding JavaScript to HTML
  2. Event Handling in HTML
  3. Working with the DOM (Document Object Model)
  4. Basic JavaScript Interactivity

1. Adding JavaScript to HTML

JavaScript can be added to an HTML document in three ways:

  1. Inline JavaScript (inside an HTML element)
  2. Internal JavaScript (inside a <script> tag in the HTML file)
  3. External JavaScript (using an external .js file)

1.1 Inline JavaScript (Using the onclick Attribute)

Inline JavaScript is written directly inside an HTML tag using attributes like onclick, onmouseover, etc.

Example: Changing text on button click

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Inline JavaScript Example</title>
</head>
<body>
    <p id="message">Click the button to change this text.</p>
    <button onclick="document.getElementById('message').innerText = 'Hello, JavaScript!';">
        Click Me
    </button>
</body>
</html>

Advantages: Quick and simple for small tasks.
Disadvantages: Hard to maintain in large projects.


1.2 Internal JavaScript (Using <script> in HTML)

Internal JavaScript is placed inside a <script> tag, typically within the <head> or at the bottom of the <body>.

Example: Changing the background color on button click

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Internal JavaScript Example</title>
    <script>
        function changeColor() {
            document.body.style.backgroundColor = "lightblue";
        }
    </script>
</head>
<body>
    <button onclick="changeColor()">Change Background</button>
</body>
</html>

Advantages: Keeps JavaScript organized within the HTML file.
Disadvantages: Still mixes JavaScript with HTML, reducing readability.


1.3 External JavaScript (Using a .js File)

External JavaScript is stored in a separate .js file and linked to the HTML file using the <script> tag.

Example: Using an external JavaScript file

HTML File (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <title>External JavaScript Example</title>
    <script src="script.js"></script>
</head>
<body>
    <p id="demo">JavaScript can make web pages interactive.</p>
    <button onclick="changeText()">Click Me</button>
</body>
</html>

External JavaScript File (script.js)

function changeText() {
    document.getElementById("demo").innerText = "You clicked the button!";
}

Advantages:
✔ Best for large projects.
✔ Keeps HTML clean and JavaScript organized.
✔ Can be reused across multiple HTML pages.

Disadvantages: Requires an extra HTTP request to load the file.


2. Event Handling in HTML

JavaScript can respond to user interactions using events like clicks, key presses, mouse movements, and more.

2.1 Common JavaScript Events

EventDescription
onclickWhen an element is clicked
onmouseoverWhen the mouse hovers over an element
onmouseoutWhen the mouse leaves an element
onkeydownWhen a key is pressed
onkeyupWhen a key is released
onloadWhen the page finishes loading

2.2 Handling Events in JavaScript

Instead of using inline event attributes, a better approach is to use JavaScript’s addEventListener().

Example: Changing text when clicking a button

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Event Handling Example</title>
</head>
<body>
    <p id="eventMessage">Click the button below.</p>
    <button id="eventButton">Click Me</button>

    <script>
        document.getElementById("eventButton").addEventListener("click", function() {
            document.getElementById("eventMessage").innerText = "Button clicked!";
        });
    </script>
</body>
</html>

Why Use addEventListener()?
✔ Keeps JavaScript separate from HTML.
✔ Allows multiple event handlers on a single element.
✔ More flexible than inline event attributes.


3. Working with the DOM (Document Object Model)

The DOM (Document Object Model) represents the HTML structure as a tree of objects, allowing JavaScript to manipulate elements dynamically.

3.1 Selecting Elements in JavaScript

We can select and modify elements using various methods:

MethodDescription
document.getElementById(id)Selects an element by its id
document.getElementsByClassName(class)Selects elements by class
document.getElementsByTagName(tag)Selects elements by tag name
document.querySelector(selector)Selects the first matching element
document.querySelectorAll(selector)Selects all matching elements

3.2 Modifying HTML Elements

Example: Changing text content

document.getElementById("demo").innerText = "New text!";

Example: Changing CSS style

document.getElementById("demo").style.color = "red";

Example: Hiding and Showing Elements

document.getElementById("demo").style.display = "none"; // Hides element
document.getElementById("demo").style.display = "block"; // Shows element

4. Basic JavaScript Interactivity

JavaScript allows us to create interactive elements like:

  • Toggling content
  • Validating forms
  • Creating animations

4.1 Toggle Visibility of a Section

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Toggle Visibility</title>
    <script>
        function toggleText() {
            let text = document.getElementById("hiddenText");
            if (text.style.display === "none") {
                text.style.display = "block";
            } else {
                text.style.display = "none";
            }
        }
    </script>
</head>
<body>
    <button onclick="toggleText()">Show/Hide Text</button>
    <p id="hiddenText" style="display: none;">This is hidden text.</p>
</body>
</html>

✅ Click the button to show or hide the text dynamically.


Conclusion

In this chapter, we learned how to:

  • Add JavaScript to HTML using inline, internal, and external methods.
  • Handle events like clicks and keypresses.
  • Work with the DOM to modify elements dynamically.
  • Create interactive effects like toggling visibility.

By mastering these JavaScript basics, you can add dynamic behavior to your webpages.

Scroll to Top