JS Example

JavaScript can be incorporated into your HTML code in three primary locations: within the <body> tag, within the <head> tag, and in an external JavaScript file. Below are examples demonstrating each method.

Let’s create the first JavaScript example:

<script type="text/javascript">
    document.write("Hello, this is way to code technologies.");
  </script>

The script tag specifies that we are using JavaScript.

The text/javascript is the content type that provides information to the browser about the data.

The document.write() function is used to display dynamic content through JavaScript. We will learn about document object in detail later.

3 Places to put JavaScript code

1. within the body tag of html

2. Within the head tag of html

3. In .js file (external javaScript)

Within the <body> Tag

Including JavaScript within the <body> tag allows the script to run as the HTML is rendered.

Example:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript Example</title>

</head>

<body>

  <h3>JavaScript Example</h3>

  <script type="text/javascript">
    document.write("javaScript within body tag.");
  </script>

</body>
</html>

Within the <head> Tag

Including JavaScript within the <head> tag ensures that the script is read before the page content is loaded.

Example:

<!DOCTYPE html>
<html>
<head>

  <title>JavaScript Example</title>

  <script type="text/javascript">
    function displayMessage() {
      document.write("JavaScript is a simple language for learners.");
    }
  </script>

</head>

<body>

  <h3>JavaScript Example</h3>

  <script type="text/javascript">
    displayMessage();
  </script>

</body>
</html>