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.β π