HTML JavaScript

Learn how to add interactivity to your web pages with JavaScript

⚡ What is JavaScript in HTML?

JavaScript makes web pages interactive. You can add JavaScript to HTML using the <script> tag to create dynamic content, handle events, and respond to user actions.

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

Output:

Key JavaScript Concepts

🎯

Events

Respond to user interactions

<button onclick="myFunction()">Click</button>
🔄

Dynamic Content

Change HTML content dynamically

document.getElementById("demo").innerHTML = "New text";
🎨

Style Changes

Modify CSS styles with JavaScript

element.style.color = "red";

Form Validation

Validate user input

if (input.value === "") {
  alert("Required!");
}

🔹 Adding JavaScript to HTML

There are three ways to add JavaScript to HTML:

<!-- 1. Inline JavaScript -->
<button onclick="alert('Inline JS')">Click Me</button>

<!-- 2. Internal JavaScript -->
<script>
function showMessage() {
    alert('Internal JS');
}
</script>

<!-- 3. External JavaScript -->
<script src="script.js"></script>

Output:

🔹 Common JavaScript Events

JavaScript can respond to various user events:

<!-- Click event -->
<button onclick="changeText()">Change Text</button>

<!-- Mouse events -->
<div onmouseover="changeColor()" 
     onmouseout="resetColor()">
    Hover over me
</div>

<!-- Form events -->
<input type="text" 
       onchange="validateInput()"
       placeholder="Type something">

Output:

Hover over me

🔹 Simple JavaScript Example

Here's a complete example showing JavaScript in action:

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Example</title>
</head>
<body>
    <h1 id="heading">Original Text</h1>
    <button onclick="changeHeading()">Change Heading</button>
    <button onclick="changeColor()">Change Color</button>

    <script>
    function changeHeading() {
        document.getElementById("heading").innerHTML = "Text Changed!";
    }
    
    function changeColor() {
        document.getElementById("heading").style.color = "blue";
    }
    </script>
</body>
</html>

Output:

Original Text

🧠 Test Your Knowledge

Which HTML tag is used to add JavaScript to a web page?