HTML + JavaScript Integration

πŸ”Œ How HTML Works with JavaScript

JavaScript is the scripting language that brings interactivity to HTML pages. While HTML structures the content and layout, JavaScript makes it dynamic β€” like responding to clicks, validating forms, and changing the DOM. πŸ’₯

>>β€œHTML is the skeleton. JavaScript gives it life.” ⚑

πŸ“Œ Adding JavaScript to HTML

JavaScript can be added to HTML in three main ways:

  • 🧩 Inline: Directly inside an HTML element
  • 🧠 Internal: Inside a <script> tag in the HTML file
  • πŸ”— External: Linked from a separate .js file

πŸ“ Inline JavaScript

Inline JS Example

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

Avoid using inline JS in production. It's great for learning, but not ideal for performance or maintainability.

πŸ“‚ Internal JavaScript

Internal JS inside script tag

<script>
  function sayHi() {
    alert('Hi from JS!');
  }
</script>

<button onclick="sayHi()">Say Hi</button>

Note

πŸ’‘ Place internal scripts at the bottom of the <body> to avoid blocking page rendering.

🧾 External JavaScript

Keeping JS in separate files helps keep your HTML clean and encourages code reuse.

External JS File

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

main.js

function greet() {
  alert('Hello from external JS!');
}

Make sure the file main.js is in the correct path relative to your HTML file.

βš™οΈ DOM Manipulation Example

Let's create a simple interaction: changing text on a button click.

HTML

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

JavaScript

function changeText() {
  document.getElementById("demo").innerText = "Text Changed!";
}

Failed to load SVG

Note

⚠️ Always test your JavaScript in multiple browsers to ensure compatibility.

πŸ” Best Practices

  • 🎯 Keep JavaScript in separate files
  • πŸ”’ Validate user input to prevent malicious scripts
  • πŸ§ͺ Use console.log() for debugging
  • πŸ’¬ Use meaningful function and variable names

πŸ“˜ Useful Links

>>β€œJavaScript turns the web from a magazine into a playground.” πŸ›