Integrating HTML with JavaScript
HTML (Hypertext Markup Language) and JavaScript are essential technologies for creating dynamic and interactive web pages. Here's a detailed guide on how to integrate HTML with JavaScript, covering various methods to include JavaScript code in HTML documents.
- Inline JavaScript
- Inline JavaScript code is placed directly within HTML tags using the on event attributes. Example:
- Pros: Quick and easy for simple actions.
- Cons:Not recommended for complex scripts due to maintainability issues.
- Internal JavaScript
- Internal JavaScript is embedded directly within the HTML file using the <script> element. Example:
- Pros: Keeps scripts within the HTML file.
- Cons: Limited reusability, especially in larger projects.
- External JavaScript
- External JavaScript involves creating a separate JS file and linking it to the HTML file.
<button onclick="alert('Hello, Coders!')">Click me</button>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Internal JavaScript</title> </head> <button onclick="showMessage()">Click me</button> <script> function showMessage() { alert('Hello, Coders!'); } </script> </body> </html>
output:-
script.js
// script.js
function showMessage() {
alert('Hello, World!');
}
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>External JavaScript</title> <script src="script.js"></script> </head> <body> <button onclick="showMessage()">Click me</button> </body> </html>