HTML with JavaScript | Adding Interactivity to Webpages

JavaScript is a scripting language used to create dynamic and interactive web content. When combined with HTML, JavaScript enhances the functionality of webpages by enabling features like form validation, content updates, animations, and event handling.

Including JavaScript in HTML:

You can include JavaScript in an HTML document in three ways:

Example of Inline JavaScript


<!DOCTYPE html>
<html>
<head>
    <title>Inline JavaScript Example</title>
</head>
<body>
    <button onclick="alert('Hello, World!')">Click Me</button>
</body>
</html>

Output

Example of Internal JavaScript


<!DOCTYPE html>
<html>
<head>
    <title>Internal JavaScript Example</title>
    <script>
        function displayMessage() {
            alert('Hello from Internal JavaScript!');
        }
    </script>
</head>
<body>
    <button onclick="displayMessage()">Click Me</button>
</body>
</html>

Output

Example of External JavaScript

<!DOCTYPE html>
<html>
    <head>
        <title>External JavaScript Example</title>
        <script src="script.js"></script>
    </head>
    <body>
        <button onclick="displayMessage()">Click Me</button>
    </body>
</html>

/* 
script.js file
function displayMessage() {
    alert('Hello from External JavaScript!');
}
*/

Output

Benefits of Using JavaScript with HTML:

Best Practices:

Combining JavaScript with HTML is a powerful way to create feature-rich and user-friendly websites. Start experimenting with basic examples and gradually build more complex functionality as you progress in your learning journey.