OneBite.Dev - Coding blog in a bite size

embedded javascript in html

Code snippet for how to how to embedded javascript in html with sample and detail explanation

Javascript is an integral part of web development, significantly enhancing HTML by making your website’s content interactive. This article shows you how to embed Javascript in HTML to add dynamic features to your static website.

Code Snippet: External Javascript File

Let’s begin with an HTML file and a separate Javascript file.

<!DOCTYPE html>
<html>
<head>
  <title>My First Javascript Webpage</title>
  <script src="script.js"></script>
</head>
<body>
  <h1>JavaScript is here!</h1>
  <button onclick="displayMessage()">Click me</button>
</body>
</html>

Next, the script.js Javascript file:

function displayMessage() {
  alert('Hello, World!');
}

Code Explanation: External Javascript File

In the HTML file, the <script> tag points to the Javascript file using the src attribute. This attribute should contain the path to your Javascript file. Here, the file script.js is in the same directory as the HTML file.

The <button> element uses the onclick event handler to invoke the displayMessage function defined in the Javascript file. When you press the button on the webpage, a pop-up alert saying ‘Hello, World!’ appears.

Code Snippet: Inline Javascript

Alternatively, you can embed Javascript directly into your HTML files using the <script> tag. Here’s an example:

<!DOCTYPE html>
<html>
<head>
  <title>My First Javascript Webpage</title>
</head>
<body>
  <h1>JavaScript is here!</h1>
  <button onclick="displayMessage()">Click me</button>

  <script>
  function displayMessage() {
    alert('Hello, World!');
  }
  </script>
</body>
</html>

Code Explanation: Inline Javascript

With inline Javascript, the <script> tag is placed directly within the HTML file, rather than linked externally. The Javascript code sits between the opening <script> and closing </script> tags.

In this example, the displayMessage function is again defined within the <script> tag. When the button is clicked, it calls this function, and ‘Hello, World!’ is displayed.

Use the method that best suits your needs. If you have plenty of Javascript code, it might make more sense to use an external file to keep your HTML file clean. If you only have a bit of Javascript, inline embedding could be more convenient.

javascript