HTML Tutorial: HTML JavaScript
Learn how to add JavaScript to HTML pages for interactivity with colorful examples, inputs, and outputs
JavaScript (JS) adds interactivity to your HTML pages. You can manipulate content, handle events, and create dynamic behavior.
1️⃣ Inline JavaScript
INPUT:
<button onclick="alert('Hello, World!')">
Click Me
</button>
OUTPUT:
✔️ Click the button to trigger JavaScript alert
✔️ Inline JS uses onclick attribute
2️⃣ Internal JavaScript
INPUT:
<!DOCTYPE html>
<html>
<head>
<script>
function showMessage() {
document.getElementById('demo').innerHTML =
'Hello from JavaScript!';
}
</script>
</head>
<body>
demo
">Original Text
</body>
</html>
OUTPUT:
Original Text
✔️ Clicking the button updates the text inside the p element
✔️ Uses getElementById and innerHTML
3️⃣ External JavaScript
INPUT:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
External File (script.js):
function greetUser() {
alert('Welcome to My Website!');
}
OUTPUT:
✔️ External JS keeps HTML clean ✔️ JS functions are defined in a separate file
4️⃣ Changing Styles with JS
INPUT:
Color me!
OUTPUT:
Color me!
✔️ JS can dynamically change CSS properties ✔️ Useful for interactive effects like hover, click, or animation
5️⃣ Best Practices for JavaScript in HTML
- Use external JS files for better organization
- Minimize inline JS for cleaner HTML
- Always test functions before deploying
- Use meaningful function and variable names
- Ensure accessibility and performance
🚀 What’s Next?
👉 HTML File Paths
Next lesson will cover:
- Relative vs absolute paths
- Linking CSS, JS, images, and files
- Practical examples for file organization
Adding JavaScript to HTML pages makes websites interactive and dynamic, enhancing user experience with events and DOM manipulation.