HTML JavaScript

JavaScript makes web pages interactive. HTML builds the structure, CSS styles it, and JavaScript adds behavior — responding to clicks, validating forms, loading data without refreshing the page, and much more. This topic focuses on how JavaScript connects to HTML using the <script> tag.

How HTML, CSS, and JavaScript Work Together

Visual Diagram — The Three Layers

Layer           Role               Analogy
------------    ---------------    --------------------------
HTML            Structure          Skeleton of a building
CSS             Appearance         Paint, furniture, lighting
JavaScript      Behavior           Electricity, doors, lifts

User clicks button → JavaScript responds → HTML updates → CSS re-styles

The script Tag

You add JavaScript to an HTML page using the <script> tag. JavaScript can go inside the tag directly or be loaded from an external file.

Inline JavaScript

<script>
  alert("Hello from JavaScript!");
</script>

External JavaScript File

<script src="app.js"></script>

The src attribute points to the JavaScript file. The script tag itself must remain empty — any code you write between the tags is ignored when src is used.

Where to Place the Script Tag

The position of the <script> tag affects page loading speed and behavior.

Visual Diagram — Script Placement

Option 1 — Inside <head>:
  HTML starts loading → hits <script> → STOPS → downloads + runs JS → resumes HTML
  Problem: page appears blank while JavaScript downloads

Option 2 — Before </body> (recommended):
  HTML loads completely → page visible to user → <script> downloads + runs
  Benefit: user sees the page faster

Option 3 — Inside <head> with defer attribute:
  HTML loads → JS downloads in background (doesn't block) → HTML finishes → JS runs
  Best of both worlds: early declaration, no blocking

Recommended: Before Closing body Tag

<body>
  <h1>My Page</h1>
  <p>Content here...</p>

  <!-- Script at the bottom -->
  <script src="app.js"></script>
</body>

Using the defer Attribute

<head>
  <script src="app.js" defer></script>
</head>

defer downloads the script in the background while HTML loads. The script runs after the entire HTML document is parsed. This keeps the declaration in the head and avoids blocking the page.

The async Attribute

<script src="analytics.js" async></script>

async downloads the script in the background and runs it as soon as it downloads — without waiting for HTML to finish loading. Use async for independent scripts like analytics that do not depend on the page content.

defer vs async Comparison

Attribute    Download         When It Runs              Use For
---------    ---------------  ------------------------  --------------------------
(none)       Blocks HTML      Immediately               Small scripts, critical code
defer        Background       After HTML fully parsed   Most page scripts
async        Background       As soon as downloaded     Independent scripts (analytics)

Selecting HTML Elements with JavaScript

JavaScript reads and changes HTML through the Document Object Model (DOM). The DOM treats every HTML tag as an object that JavaScript can find, modify, or remove.

<p id="greeting">Hello!</p>

<script>
  // Find the element with id="greeting"
  const para = document.getElementById("greeting");

  // Change its text content
  para.textContent = "Welcome to eStudy247!";
</script>

Common DOM Selection Methods

document.getElementById("id")          → finds one element by id
document.querySelector(".class")       → finds first element matching CSS selector
document.querySelectorAll("p")         → finds all elements matching selector
document.getElementsByClassName("cls") → finds all elements with that class
document.getElementsByTagName("div")   → finds all elements with that tag

Reacting to User Events

JavaScript listens for user actions — clicks, key presses, form submissions — using event listeners.

Click Event

<button id="myBtn">Click Me</button>
<p id="result"></p>

<script>
  document.getElementById("myBtn").addEventListener("click", function() {
    document.getElementById("result").textContent = "Button was clicked!";
  });
</script>

Inline Event Handler (Older Style)

<button onclick="showMessage()">Click Me</button>

<script>
  function showMessage() {
    alert("Hello!");
  }
</script>

The modern addEventListener approach is preferred because it separates JavaScript from HTML and lets you add multiple listeners to one element.

Changing HTML Content

<div id="box">Original text</div>

<script>
  const box = document.getElementById("box");

  // Change text only (safer)
  box.textContent = "New text content";

  // Change HTML inside (allows tags)
  box.innerHTML = "<strong>Bold new text</strong>";
</script>

Use textContent for plain text. Use innerHTML only when you need to insert HTML tags.

Changing CSS with JavaScript

<p id="note">This text changes color</p>

<script>
  const note = document.getElementById("note");
  note.style.color = "red";
  note.style.fontSize = "24px";
  note.style.backgroundColor = "#ffffcc";
</script>

CSS property names in JavaScript use camelCase — background-color becomes backgroundColor.

Showing and Hiding Elements

<div id="panel">This panel can be hidden</div>
<button id="toggleBtn">Toggle</button>

<script>
  document.getElementById("toggleBtn").addEventListener("click", function() {
    const panel = document.getElementById("panel");
    if (panel.style.display === "none") {
      panel.style.display = "block";
    } else {
      panel.style.display = "none";
    }
  });
</script>

Form Validation with JavaScript

<form id="loginForm">
  <input type="text" id="username" placeholder="Username">
  <button type="submit">Login</button>
  <p id="error" style="color:red;"></p>
</form>

<script>
  document.getElementById("loginForm").addEventListener("submit", function(e) {
    const username = document.getElementById("username").value;

    if (username.trim() === "") {
      e.preventDefault();   // stop form from submitting
      document.getElementById("error").textContent = "Username cannot be empty.";
    }
  });
</script>

The noscript Tag

The <noscript> tag displays content only when a browser has JavaScript disabled. Use it to tell users that your page requires JavaScript.

<noscript>
  <p>This page requires JavaScript. Please enable JavaScript in your browser settings.</p>
</noscript>

script Type Attribute

The type attribute on <script> tells the browser what kind of script is inside.

<!-- Default JavaScript (type can be omitted in modern HTML) -->
<script type="text/javascript">...</script>

<!-- JavaScript module (supports import/export) -->
<script type="module" src="main.js"></script>

<!-- Template or data (browser ignores the content as code) -->
<script type="application/json" id="data">
  {"name":"Alice","score":95}
</script>

Loading JavaScript Best Practices

✓ Place scripts before </body> or use defer in <head>
✓ Use external .js files — keep JS separate from HTML
✓ Use addEventListener instead of inline onclick
✓ Use id attributes on elements you need to target
✓ Add <noscript> message for JavaScript-dependent pages
✓ Use type="module" for modern ES6+ module code

HTML provides the foundation, and JavaScript builds on top of it. Understanding how the script tag works, where to place it, and how JavaScript finds HTML elements gives you the knowledge to start making your pages interactive.

Leave a Comment

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