HTML JavaScript

JavaScript is a powerful scripting language that makes HTML pages dynamic. While HTML creates the structure of a webpage, JavaScript adds logic and interaction. Simply put, HTML tells you what to display, and JavaScript tells you how to execute it.

When you add JavaScript code to an HTML page, the browser reads that script and executes it step-by-step. There are two ways to add JavaScript to HTML,

1. Internal JavaScript

Internal JavaScript is written within the <script> tag in your HTML file. It can be placed in the <head> or <body> section.

<!DOCTYPE html>
<html>
<head>
  <title>Internal JavaScript Example</title>
  <script>
    function showMessage() {
      alert("Welcome to HTML JavaScript Tutorial!");
    }
  </script>
</head>
<body>

<h2>Click the Button Below</h2>
<button onclick="showMessage()">Click Me</button>

</body>
</html>

πŸ’‘ Tip: Keep JavaScript at the end of the body for faster page loading.

2. External JavaScript

It’s a best practice to store JavaScript in a separate .js file and link it using the <script> tag. This makes your code clean, organized, and reusable.

Example:

HTML File (index.html):

<!DOCTYPE html>
<html>
<head>
  <title>External JavaScript Example</title>
  <script src="script.js"></script>
</head>
<body>

<h2>External JavaScript Example</h2>
<button onclick="displayDate()">Show Date</button>

</body>
</html>

External JS File (script.js):

function displayDate() {
  alert("Today’s Date is: " + new Date());
}

Explanation: The <script src=”script.js”> line links your external JavaScript file to the HTML document.

Inline JavaScript

You can also add JavaScript directly inside HTML tags using event attributes like onclick, onmouseover, etc.

Example:

<!DOCTYPE html>
<html>
<head>
  <title>Inline JavaScript Example</title>
</head>
<body>

<h2>Inline JavaScript Example</h2>
<button onclick="alert('Button Clicked!')">Click Me</button>

</body>
</html>

πŸ’‘ Tip: Use inline JavaScript only for simple, small tasks. For complex scripts, prefer internal or external JS.

Where Should You Place JavaScript in HTML?

You can place the <script> tag in,

The <head> section – runs before page content loads

The <body> section – runs after content is displayed

πŸ’‘ Best Practice: Always place JavaScript just before the closing </body> tag for better page speed.

Example of Full HTML Page with JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>HTML JavaScript Full Example</title>
</head>
<body>

<h2>Welcome to HTML JavaScript</h2>
<p>Click the button to change the background color:</p>

<button onclick="changeColor()">Change Color</button>

<script>
function changeColor() {
  document.body.style.backgroundColor = "lightgreen";
}
</script>

</body>
</html>

πŸ’‘ Explanation: The document.body.style property changes the background color using JavaScript DOM manipulation.

Leave a Comment