JS Use Case

Introduction to JavaScript in HTML

JavaScript is a powerful scripting language that allows you to create dynamic and interactive web pages. By integrating JavaScript with HTML, you can enhance the user experience by adding features like form validation, interactive maps, and dynamic content updates.

Ways to Use JavaScript in HTML

There are three main ways to include JavaScript in your HTML:

  1. Inline JavaScript
  2. Internal JavaScript
  3. External JavaScript

1. Inline JavaScript

Inline JavaScript is written directly within an HTML element’s attribute. This method is useful for small scripts.

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

In this example, the onclick attribute of the button element contains a JavaScript function that displays an alert box when the button is clicked.

2. Internal JavaScript

Internal JavaScript is written within the <script> tags inside the HTML document. This method is useful for scripts that are specific to a single HTML page.

<!DOCTYPE html>
<html>
<head>
    <title>Internal JavaScript Example</title>
    <script>
        function showMessage() {
            document.getElementById("message").innerHTML = "Hello, World!";
        }
    </script>
</head>
<body>
    <button onclick="showMessage()">Click Me!</button>
    <p id="message"></p>
</body>
</html>

In this example, the JavaScript function showMessage is defined within the <script> tags and is called when the button is clicked, updating the content of the paragraph with the id “message”.

3. External JavaScript

External JavaScript is written in a separate .js file and linked to the HTML document using the <script> tag with the src attribute. This method is useful for larger scripts that are used across multiple HTML pages.

HTML File:

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

JavaScript File (script.js):

JavaScript File (script.js):

In this example, the JavaScript function showMessage is defined in an external file script.js and is linked to the HTML document. When the button is clicked, the function updates the content of the paragraph with the id “message”.

Conclusion

Using JavaScript in HTML allows you to create more interactive and dynamic web pages. Whether you choose to use inline, internal, or external JavaScript depends on the complexity and reusability of your scripts. Experiment with these methods to see which works best for your projects!

Share this Tutorials

JS Use Case

Or copy link

CONTENTS
Scroll to Top