Skip to content

How to use JavaScript in HTML

  • by

JavaScript can be used in an HTML document in a few different ways. Here are three common methods:

1. Inline JavaScript: This involves adding JavaScript code directly to an HTML element using the “onclick” attribute.

<button onclick="alert('Hello, World!')">Click me</button>

2. Internal JavaScript: This involves placing JavaScript code within the <script> element, which is typically placed in the head or body section of the HTML document.

<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
    <script>
      function myFunction() {
        document.getElementById("demo").innerHTML = "Hello, World!";
      }
    </script>
  </head>
  <body>
    <button onclick="myFunction()">Click me</button>
    <p id="demo"></p>
  </body>
</html>

3. External JavaScript: This involves linking to an external JavaScript file using the <script> element’s “src” attribute.

<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
    <script src="myScript.js"></script>
  </head>
  <body>
    <button onclick="myFunction()">Click me</button>
    <p id="demo"></p>
  </body>
</html>

Use JavaScript in HTML example

A simple example code uses JavaScript in HTML to validate a form:

<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
    <script>
      function validateForm() {
        const name = document.forms["myForm"]["name"].value;
        const email = document.forms["myForm"]["email"].value;
        if (name === "") {
          alert("Please enter your name");
          return false;
        }
        if (email === "") {
          alert("Please enter your email");
          return false;
        }
      }
    </script>
  </head>
  <body>
    <h1>My Form</h1>
    <form name="myForm" onsubmit="return validateForm()">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name"><br><br>
      <label for="email">Email:</label>
      <input type="email" id="email" name="email"><br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Output:

How to use JavaScript in HTML

You can also use JavaScript events to trigger actions on your web page. For example, you can use the onclick event to run a function when a button is clicked.

<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
    <script src="myscript.js"></script>
  </head>
  <body>
    <h1>Welcome to my web page</h1>
    <p>Click the button to change the text color:</p>
    <button onclick="changeColor()">Click me</button>
  </body>
</html>

Comment if you have any doubts or suggestions on this JS HTML topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *