12. JavaScript Events – Programs

onclick Event

Program 1: Display Alert on Click

				
					<button onclick="showAlert()">Click Here</button>

<script>
function showAlert() {
  alert("Button clicked successfully");
}
</script>

				
			

Program 2: Change Text on Click

				
					<p id="msg">Initial Text</p>
<button onclick="changeText()">Change Text</button>

<script>
function changeText() {
  document.getElementById("msg").innerText = "Text updated using onclick";
}
</script>

				
			

ondblclick Event

Program 3: Double Click to Change Color

				
					<p ondblclick="changeColor(this)">Double click me</p>

<script>
function changeColor(el) {
  el.style.color = "blue";
}
</script>

				
			

Program 4: Double Click to Show Message

				
					<div ondblclick="showMsg()" style="border:1px solid;padding:10px;">
Double click inside box
</div>

<script>
function showMsg() {
  alert("Double click detected");
}
</script>

				
			

onsubmit Event

Program 5: Basic Form Submission

				
					<form onsubmit="return submitForm()">
  <input type="text" required>
  <button type="submit">Submit</button>
</form>

<script>
function submitForm() {
  alert("Form submitted");
  return true;
}
</script>

				
			

Program 6: Prevent Submit if Field Empty

				
					<form onsubmit="return validateForm()">
  <input type="text" id="user">
  <button>Send</button>
</form>

<script>
function validateForm() {
  if (document.getElementById("user").value === "") {
    alert("Field cannot be empty");
    return false;
  }
  return true;
}
</script>

				
			

onmouseover Event

Program 7: Highlight Box

				
					<div onmouseover="hoverIn(this)"
style="width:200px;height:100px;background:#ccc;">
Hover here
</div>

<script>
function hoverIn(el) {
  el.style.background = "lightgreen";
}
</script>

				
			

Program 8: Change Text on Hover

				
					<p onmouseover="this.innerText='Mouse is over text'">
Hover on this text
</p>

				
			

onmouseout Event

Program 9: Reset Background Color

				
					<div onmouseout="resetBg(this)"
style="width:200px;height:100px;background:orange;">
Move mouse out
</div>

<script>
function resetBg(el) {
  el.style.background = "orange";
}
</script>

				
			

Program 10: Message on Mouse Out

				
					<p onmouseout="alert('Mouse left the area')">
Move mouse away
</p>

				
			

onfocus Event

Program 11: Highlight Input on Focus

				
					<input type="text" onfocus="focusField(this)">

<script>
function focusField(el) {
  el.style.background = "#ffffcc";
}
</script>

				
			

Program 12: Border Change on Focus

				
					<input type="text" onfocus="this.style.border='2px solid green'">
				
			

onblur Event

Program 13: Convert Text to Uppercase

				
					<input type="text" id="name" onblur="makeUpper()">

<script>
function makeUpper() {
  let v = document.getElementById("name").value;
  document.getElementById("name").value = v.toUpperCase();
}
</script>

				
			

Program 14: Validation on Blur

				
					<input type="text" id="email" onblur="checkEmail()">

<script>
function checkEmail() {
  if (!email.value.includes("@")) {
    alert("Invalid email");
  }
}
</script>

				
			

onchange Event

Program 15: Display Selected Option

				
					<select onchange="showValue(this.value)">
  <option>HTML</option>
  <option>CSS</option>
  <option>JS</option>
</select>

<p id="out"></p>

<script>
function showValue(val) {
  out.innerText = "Selected: " + val;
}
</script>

				
			

Program 16: Change Background Based on Selection

				
					<select onchange="document.body.style.background=this.value">
  <option value="white">White</option>
  <option value="lightblue">Blue</option>
</select>

				
			

onkeydown Event

Program 17: Show Key Pressed

				
					<input type="text" onkeydown="keyDown(event)">

<script>
function keyDown(e) {
  console.log("Key:", e.key);
}
</script>

				
			

Program 18: Block Number Keys

				
					<input type="text" onkeydown="return noNumbers(event)">

<script>
function noNumbers(e) {
  return !(e.key >= 0 && e.key <= 9);
}
</script>

				
			

onkeyup Event

Program 19: Character Counter

				
					<input type="text" id="txt" onkeyup="count()">
<p id="len"></p>

<script>
function count() {
  len.innerText = txt.value.length;
}
</script>

				
			

Program 20: Live Uppercase

				
					<input type="text" onkeyup="this.value=this.value.toUpperCase()">
				
			

onload Event

Program 21: Alert on Page Load

				
					<body onload="pageReady()">

<script>
function pageReady() {
  alert("Page loaded");
}
</script>

				
			

Program 22: Initialize Content on Load

				
					<body onload="document.body.style.background='lightgray'">
				
			

onmousedown Event

Program 23: Detect Mouse Press

				
					<div onmousedown="alert('Mouse button pressed')">
Click and hold
</div>

				
			

Program 24: Change Text on Mouse Down

				
					<p onmousedown="this.innerText='Mouse pressed'">
Press mouse here
</p>

				
			

onmouseup Event

Program 25: Detect Mouse Release

				
					<div onmouseup="alert('Mouse released')">
Release mouse here
</div>

				
			

Program 26: Restore Text on Release

				
					<p onmouseup="this.innerText='Mouse released'">
Release mouse
</p>

				
			

onmousemove Event

Program 27: Log Mouse Movement

				
					<p onmousemove="console.log('Mouse moving')">
Move mouse here
</p>

				
			

Program 28: Show Coordinates

				
					<p onmousemove="showPos(event)"></p>

<script>
function showPos(e) {
  event.target.innerText = `X:${e.clientX}, Y:${e.clientY}`;
}
</script>

				
			

onerror Event

Program 29: Image Load Error

				
					<img decoding="async" src="missing.png" onerror="alert('Image not found')">
				
			

Program 30: Replace Image on Error

				
					<img decoding="async" src="wrong.jpg" onerror="this.src='default.jpg'">
				
			

onresize Event

Program 31: Detect Resize

				
					<body onresize="alert('Window resized')">
				
			

Program 32: Show Width on Resize

				
					<body onresize="console.log(window.innerWidth)">
				
			

onselect Event

Program 33: Alert on Text Select

				
					<input type="text" value="Select this text" onselect="alert('Text selected')">
				
			

Program 34: Change Color on Selection

				
					<input type="text" value="Select me" onselect="this.style.background='yellow'">

				
			

onunload Event

Program 35: Alert Before Leaving

				
					<body onunload="alert('Leaving page')">
				
			

Program 36: Log Page Exit

				
					<body onunload="console.log('Page unloaded')">
				
			

Button Interaction Panel

Use onclick, ondblclick to show messages, change text, and toggle colors.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Button Interaction Panel</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    #panel {
      width: 300px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 20px;
      text-align: center;
      background-color: #f2f2f2;
    }

    button {
      padding: 10px 15px;
      margin: 5px;
      cursor: pointer;
    }
  </style>
</head>

<body>

  <h2>Button Interaction Panel</h2>

  <!-- Buttons -->
  <button onclick="showMessage()">Single Click</button>
  <button ondblclick="toggleColor()">Double Click</button>

  <!-- Interaction Panel -->
  <div id="panel">
    <p id="text">No action performed yet</p>
  </div>

  <script>
    // onclick event function
    function showMessage() {
      document.getElementById("text").innerText =
        "Button clicked using onclick event";
    }

    // ondblclick event function
    function toggleColor() {
      let panel = document.getElementById("panel");

      if (panel.style.backgroundColor === "lightgreen") {
        panel.style.backgroundColor = "#f2f2f2";
        panel.style.color = "black";
      } else {
        panel.style.backgroundColor = "lightgreen";
        panel.style.color = "darkgreen";
      }

      document.getElementById("text").innerText =
        "Panel color toggled using ondblclick event";
    }
  </script>

</body>
</html>
				
			

Text Formatter Tool

Convert input text to uppercase/lowercase using onblur, onkeyup.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Text Formatter Tool</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .box {
      width: 300px;
      padding: 15px;
      border: 2px solid #444;
      margin-top: 20px;
    }

    input {
      width: 100%;
      padding: 8px;
      font-size: 16px;
    }

    p {
      margin-top: 10px;
      font-weight: bold;
    }
  </style>
</head>

<body>

  <h2>Text Formatter Tool</h2>

  <p>Type text (live uppercase using onkeyup)</p>
  <input type="text" id="textInput" onkeyup="liveUppercase()" onblur="finalLowercase()">

  <div class="box">
    <p id="output">Formatted text will appear here</p>
  </div>

  <script>
    // onkeyup event – convert to uppercase while typing
    function liveUppercase() {
      let text = document.getElementById("textInput").value;
      document.getElementById("output").innerText = text.toUpperCase();
    }

    // onblur event – convert text to lowercase when focus is lost
    function finalLowercase() {
      let text = document.getElementById("textInput").value;
      document.getElementById("output").innerText = text.toLowerCase();
    }
  </script>

</body>
</html>
				
			

Color Theme Selector

Change page background using a dropdown with onchange.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Color Theme Selector</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      transition: background-color 0.3s;
    }

    .container {
      margin-top: 40px;
      padding: 20px;
      width: 300px;
      border: 2px solid #333;
    }
  </style>
</head>

<body>

  <h2>Color Theme Selector</h2>

  <div class="container">
    <label>Select Theme Color:</label><br><br>

    <select onchange="changeTheme(this.value)">
      <option value="">-- Select Color --</option>
      <option value="white">Default</option>
      <option value="lightblue">Light Blue</option>
      <option value="lightgreen">Light Green</option>
      <option value="lightyellow">Light Yellow</option>
      <option value="lightgray">Light Gray</option>
    </select>
  </div>

  <script>
    // onchange event function
    function changeTheme(color) {
      if (color !== "") {
        document.body.style.backgroundColor = color;
      }
    }
  </script>

</body>
</html>
				
			

Mouse Activity Box

Display messages for onmouseover, onmouseout, onmousemove.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Mouse Activity Box</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    #box {
      width: 300px;
      height: 150px;
      border: 2px solid #333;
      margin-top: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f0f0f0;
      font-weight: bold;
    }

    #message {
      margin-top: 15px;
      font-size: 16px;
    }
  </style>
</head>

<body>

  <h2>Mouse Activity Box</h2>
  <p>Move your mouse over the box below</p>

  <div id="box"
       onmouseover="mouseEnter()"
       onmousemove="mouseMove()"
       onmouseout="mouseLeave()">
    Mouse Box
  </div>

  <p id="message">Waiting for mouse action...</p>

  <script>
    // onmouseover event
    function mouseEnter() {
      document.getElementById("message").innerText =
        "Mouse entered the box";
    }

    // onmousemove event
    function mouseMove() {
      document.getElementById("message").innerText =
        "Mouse is moving inside the box";
    }

    // onmouseout event
    function mouseLeave() {
      document.getElementById("message").innerText =
        "Mouse left the box";
    }
  </script>

</body>
</html>
				
			

Simple Alert Form

Show alert on form submission using onsubmit.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Simple Alert Form</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .form-box {
      width: 300px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input, button {
      width: 100%;
      padding: 8px;
      margin-top: 10px;
    }
  </style>
</head>

<body>

  <h2>Simple Alert Form</h2>

  <div class="form-box">
    <form onsubmit="return showAlert()">
      <label>Enter Your Name:</label>
      <input type="text" required>

      <button type="submit">Submit</button>
    </form>
  </div>

  <script>
    // onsubmit event function
    function showAlert() {
      alert("Form submitted successfully!");
      return true;   // allows form submission
    }
  </script>

</body>
</html>
				
			

Character Counter

Count characters in an input field using onkeyup.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Character Counter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .counter-box {
      width: 300px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input {
      width: 100%;
      padding: 8px;
      font-size: 16px;
    }

    #count {
      margin-top: 10px;
      font-weight: bold;
    }
  </style>
</head>

<body>

  <h2>Character Counter</h2>

  <div class="counter-box">
    <label>Type your text:</label>
    <input type="text" id="textInput" onkeyup="countChars()">

    <p id="count">Characters: 0</p>
  </div>

  <script>
    // onkeyup event function
    function countChars() {
      let text = document.getElementById("textInput").value;
      document.getElementById("count").innerText =
        "Characters: " + text.length;
    }
  </script>

</body>
</html>
				
			

Focus Highlighter

Highlight input fields using onfocus and remove highlight using onblur.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Focus Highlighter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .form-box {
      width: 300px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input {
      width: 100%;
      padding: 8px;
      margin-top: 10px;
      font-size: 16px;
    }
  </style>
</head>

<body>

  <h2>Focus Highlighter</h2>

  <div class="form-box">
    <label>Name:</label>
    <input type="text"
           onfocus="highlight(this)"
           onblur="removeHighlight(this)">

    <label>Email:</label>
    <input type="email"
           onfocus="highlight(this)"
           onblur="removeHighlight(this)">
  </div>

  <script>
    // onfocus event function
    function highlight(field) {
      field.style.backgroundColor = "#ffffcc";
      field.style.border = "2px solid green";
    }

    // onblur event function
    function removeHighlight(field) {
      field.style.backgroundColor = "white";
      field.style.border = "1px solid #ccc";
    }
  </script>

</body>
</html>
				
			

Image Error Handler

Show fallback message/image using onerror.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Image Error Handler</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .image-box {
      width: 300px;
      padding: 15px;
      border: 2px solid #333;
      margin-top: 30px;
      text-align: center;
    }

    img {
      width: 200px;
      height: 120px;
      border: 1px solid #ccc;
    }

    #message {
      margin-top: 10px;
      color: red;
      font-weight: bold;
    }
  </style>
</head>

<body>

  <h2>Image Error Handler</h2>
  <p>If the image fails to load, a fallback message and image will appear.</p>

  <div class="image-box">
    <img decoding="async" src="missing-image.jpg"
         alt="Sample Image"
         onerror="handleImageError(this)">

    <p id="message"></p>
  </div>

  <script>
    // onerror event function
    function handleImageError(imgElement) {
      imgElement.src = "fallback-image.jpg";   // fallback image
      document.getElementById("message").innerText =
        "Original image could not be loaded.";
    }
  </script>

</body>
</html>
				
			

Login Form Validation

Validate empty fields and email format using onsubmit + onblur.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Login Form Validation</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .login-box {
      width: 320px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input {
      width: 100%;
      padding: 8px;
      margin-top: 10px;
      font-size: 15px;
    }

    .error {
      color: red;
      font-size: 13px;
    }

    button {
      width: 100%;
      padding: 8px;
      margin-top: 15px;
    }
  </style>
</head>

<body>

  <h2>Login Form Validation</h2>

  <div class="login-box">
    <form onsubmit="return validateForm()">

      <label>Email:</label>
      <input type="text" id="email" onblur="validateEmail()">
      <div id="emailError" class="error"></div>

      <label>Password:</label>
      <input type="password" id="password" onblur="validatePassword()">
      <div id="passwordError" class="error"></div>

      <button type="submit">Login</button>
    </form>
  </div>

  <script>
    // onblur validation for email
    function validateEmail() {
      let email = document.getElementById("email").value;
      let error = document.getElementById("emailError");

      if (email === "") {
        error.innerText = "Email is required";
        return false;
      } else if (!email.includes("@") || !email.includes(".")) {
        error.innerText = "Invalid email format";
        return false;
      } else {
        error.innerText = "";
        return true;
      }
    }

    // onblur validation for password
    function validatePassword() {
      let pwd = document.getElementById("password").value;
      let error = document.getElementById("passwordError");

      if (pwd === "") {
        error.innerText = "Password is required";
        return false;
      } else if (pwd.length < 6) {
        error.innerText = "Password must be at least 6 characters";
        return false;
      } else {
        error.innerText = "";
        return true;
      }
    }

    // onsubmit validation
    function validateForm() {
      let emailValid = validateEmail();
      let pwdValid = validatePassword();

      if (emailValid && pwdValid) {
        alert("Login successful");
        return true;
      } else {
        alert("Please fix the errors before submitting");
        return false;
      }
    }
  </script>

</body>
</html>
				
			

Keyboard Activity Logger

Display pressed keys using onkeydown, onkeyup.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Keyboard Activity Logger</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .logger-box {
      width: 500px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input {
      width: 100%;
      padding: 10px;
      font-size: 16px;
      margin-top: 10px;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
    }

    .log {
      margin-top: 15px;
      height: 150px;
      overflow-y: auto;
      border: 1px solid #999;
      padding: 10px;
      background-color: #f9f9f9;
      font-size: 14px;
    }

    .down {
      color: blue;
    }

    .up {
      color: green;
    }
  </style>
</head>

<body>

  <h2>Keyboard Activity Logger</h2>
  <p>Click inside the input box and start typing.</p>

  <div class="logger-box">

    <label>Type here:</label>
    <input type="text"
           id="keyInput"
           onkeydown="keyDown(event)"
           onkeyup="keyUp(event)">

    <div class="status">
      <p>Last Key Pressed: <span id="lastDown">None</span></p>
      <p>Last Key Released: <span id="lastUp">None</span></p>
    </div>

    <div class="log" id="logBox">
      <strong>Key Activity Log:</strong><br>
    </div>

  </div>

  <script>
    // onkeydown event handler
    function keyDown(e) {
      document.getElementById("lastDown").innerText = e.key;

      let log = document.getElementById("logBox");
      log.innerHTML +=
        "<div class='down'>Key Down: " + e.key + "</div>";

      log.scrollTop = log.scrollHeight;
    }

    // onkeyup event handler
    function keyUp(e) {
      document.getElementById("lastUp").innerText = e.key;

      let log = document.getElementById("logBox");
      log.innerHTML +=
        "<div class='up'>Key Up: " + e.key + "</div>";

      log.scrollTop = log.scrollHeight;
    }
  </script>

</body>
</html>
				
			

Copy Text Utility

Copy text between fields using onclick.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Copy Text Utility</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .container {
      width: 450px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input {
      width: 100%;
      padding: 8px;
      margin-top: 10px;
      font-size: 15px;
    }

    button {
      padding: 8px 12px;
      margin-top: 10px;
      margin-right: 5px;
      cursor: pointer;
    }

    #status {
      margin-top: 15px;
      font-weight: bold;
      color: green;
    }
  </style>
</head>

<body>

  <h2>Copy Text Utility</h2>
  <p>Use the buttons to copy text between fields.</p>

  <div class="container">

    <label>Source Text:</label>
    <input type="text" id="source" placeholder="Enter text here">

    <label>Destination 1:</label>
    <input type="text" id="dest1" placeholder="Copied text will appear here">

    <label>Destination 2:</label>
    <input type="text" id="dest2" placeholder="Copied text will appear here">

    <br>

    <button onclick="copyToFirst()">Copy to Destination 1</button>
    <button onclick="copyToSecond()">Copy to Destination 2</button>
    <button onclick="copyToBoth()">Copy to Both</button>
    <button onclick="clearAll()">Clear All</button>

    <p id="status"></p>

  </div>

  <script>
    // Copy text to Destination 1
    function copyToFirst() {
      document.getElementById("dest1").value =
        document.getElementById("source").value;

      document.getElementById("status").innerText =
        "Text copied to Destination 1";
    }

    // Copy text to Destination 2
    function copyToSecond() {
      document.getElementById("dest2").value =
        document.getElementById("source").value;

      document.getElementById("status").innerText =
        "Text copied to Destination 2";
    }

    // Copy text to both destinations
    function copyToBoth() {
      let text = document.getElementById("source").value;

      document.getElementById("dest1").value = text;
      document.getElementById("dest2").value = text;

      document.getElementById("status").innerText =
        "Text copied to both fields";
    }

    // Clear all fields
    function clearAll() {
      document.getElementById("source").value = "";
      document.getElementById("dest1").value = "";
      document.getElementById("dest2").value = "";

      document.getElementById("status").innerText =
        "All fields cleared";
    }
  </script>

</body>
</html>
				
			

Window Resize Tracker

Display window width/height using onresize.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Window Resize Tracker</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      transition: background-color 0.3s;
    }

    .tracker-box {
      width: 400px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    .info {
      font-size: 18px;
      margin-top: 10px;
      font-weight: bold;
    }

    .note {
      margin-top: 15px;
      font-size: 14px;
      color: #555;
    }
  </style>
</head>

<body onresize="trackResize()">

  <h2>Window Resize Tracker</h2>
  <p>Resize the browser window to see live updates.</p>

  <div class="tracker-box">
    <div class="info">
      Width: <span id="width">0</span> px
    </div>

    <div class="info">
      Height: <span id="height">0</span> px
    </div>

    <div class="note" id="message">
      Resize the window to start tracking.
    </div>
  </div>

  <script>
    // onresize event handler
    function trackResize() {
      let w = window.innerWidth;
      let h = window.innerHeight;

      document.getElementById("width").innerText = w;
      document.getElementById("height").innerText = h;

      document.getElementById("message").innerText =
        "Window resized at " + new Date().toLocaleTimeString();

      // Visual feedback based on width
      if (w < 600) {
        document.body.style.backgroundColor = "#ffe6e6";
      } else if (w < 900) {
        document.body.style.backgroundColor = "#fff5cc";
      } else {
        document.body.style.backgroundColor = "#e6ffe6";
      }
    }

    // Initialize values on first load
    trackResize();
  </script>

</body>
</html>
				
			

Mouse Press Detector

Detect onmousedown and onmouseup to show interaction state.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Mouse Press Detector</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .detector-box {
      width: 400px;
      height: 160px;
      border: 3px solid #333;
      margin-top: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      font-weight: bold;
      background-color: #f2f2f2;
      user-select: none;
    }

    .status {
      margin-top: 15px;
      font-size: 16px;
      font-weight: bold;
    }

    .pressed {
      background-color: #ffe0e0;
      border-color: red;
      color: darkred;
    }

    .released {
      background-color: #e0ffe0;
      border-color: green;
      color: darkgreen;
    }
  </style>
</head>

<body>

  <h2>Mouse Press Detector</h2>
  <p>Press and release the mouse button inside the box.</p>

  <div id="box"
       class="detector-box"
       onmousedown="mousePressed()"
       onmouseup="mouseReleased()">
    Interaction Area
  </div>

  <div class="status" id="statusText">
    Current State: Idle
  </div>

  <script>
    // onmousedown event handler
    function mousePressed() {
      let box = document.getElementById("box");

      box.classList.add("pressed");
      box.classList.remove("released");
      box.innerText = "Mouse Button Pressed";

      document.getElementById("statusText").innerText =
        "Current State: Mouse Pressed";
    }

    // onmouseup event handler
    function mouseReleased() {
      let box = document.getElementById("box");

      box.classList.remove("pressed");
      box.classList.add("released");
      box.innerText = "Mouse Button Released";

      document.getElementById("statusText").innerText =
        "Current State: Mouse Released";
    }
  </script>

</body>
</html>
				
			

Text Selection Notifier

Detect when text is selected using onselect.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Text Selection Notifier</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .selection-box {
      width: 420px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    input {
      width: 100%;
      padding: 8px;
      font-size: 16px;
    }

    .message {
      margin-top: 15px;
      font-size: 16px;
      font-weight: bold;
      color: blue;
    }
  </style>
</head>

<body>

  <h2>Text Selection Notifier</h2>
  <p>Select any part of the text inside the input field.</p>

  <div class="selection-box">
    <input type="text"
           id="textField"
           value="Select any part of this text"
           onselect="textSelected()">

    <div class="message" id="msg">
      No text selected yet
    </div>
  </div>

  <script>
    // onselect event handler
    function textSelected() {
      let field = document.getElementById("textField");
      let start = field.selectionStart;
      let end = field.selectionEnd;

      let selectedText = field.value.substring(start, end);

      document.getElementById("msg").innerText =
        "Selected Text: \"" + selectedText + "\"";
    }
  </script>

</body>
</html>
				
			

Hover Help Tooltip

Show help text on onmouseover, hide on onmouseout.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Hover Help Tooltip</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .form-box {
      width: 420px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    label {
      display: block;
      margin-top: 15px;
      font-weight: bold;
    }

    input {
      width: 100%;
      padding: 8px;
      font-size: 15px;
    }

    .help-icon {
      display: inline-block;
      margin-left: 6px;
      width: 18px;
      height: 18px;
      line-height: 18px;
      text-align: center;
      background-color: #333;
      color: #fff;
      border-radius: 50%;
      font-size: 12px;
      cursor: pointer;
    }

    .tooltip {
      margin-top: 6px;
      padding: 8px;
      background-color: #ffffcc;
      border: 1px solid #999;
      font-size: 14px;
      display: none;
    }
  </style>
</head>

<body>

  <h2>Hover Help Tooltip</h2>
  <p>Hover over the help icons to see guidance.</p>

  <div class="form-box">

    <label>
      Username
      <span class="help-icon"
            onmouseover="showHelp('userHelp')"
            onmouseout="hideHelp('userHelp')">?</span>
    </label>
    <input type="text">

    <div class="tooltip" id="userHelp">
      Username should be at least 5 characters long.
    </div>

    <label>
      Password
      <span class="help-icon"
            onmouseover="showHelp('passHelp')"
            onmouseout="hideHelp('passHelp')">?</span>
    </label>
    <input type="password">

    <div class="tooltip" id="passHelp">
      Password must contain letters and numbers.
    </div>

  </div>

  <script>
    // onmouseover handler
    function showHelp(id) {
      document.getElementById(id).style.display = "block";
    }

    // onmouseout handler
    function hideHelp(id) {
      document.getElementById(id).style.display = "none";
    }
  </script>

</body>
</html>
				
			

Form Reset Tracker

Show message when form is reset using onreset.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Form Reset Tracker</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .form-box {
      width: 420px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    label {
      display: block;
      margin-top: 12px;
      font-weight: bold;
    }

    input {
      width: 100%;
      padding: 8px;
      margin-top: 5px;
      font-size: 15px;
    }

    button {
      margin-top: 15px;
      padding: 8px 14px;
      margin-right: 8px;
      cursor: pointer;
    }

    .message {
      margin-top: 15px;
      font-size: 16px;
      font-weight: bold;
      color: blue;
    }
  </style>
</head>

<body>

  <h2>Form Reset Tracker</h2>
  <p>Fill the form and click Reset to see the event in action.</p>

  <div class="form-box">

    <form onreset="resetMessage()">

      <label>Name:</label>
      <input type="text" value="John Doe">

      <label>Email:</label>
      <input type="email" value="john@example.com">

      <label>Course:</label>
      <input type="text" value="JavaScript">

      <button type="submit">Submit</button>
      <button type="reset">Reset</button>

    </form>

    <div class="message" id="msg">
      Form is ready
    </div>

  </div>

  <script>
    // onreset event handler
    function resetMessage() {
      document.getElementById("msg").innerText =
        "Form has been reset successfully";
    }
  </script>

</body>
</html>
				
			

Interactive Navigation Menu

Toggle menu visibility using onclick, manage hover effects.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Interactive Navigation Menu</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
    }

    /* Header */
    .header {
      background-color: #333;
      color: white;
      padding: 12px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .menu-btn {
      cursor: pointer;
      font-size: 18px;
      background-color: #555;
      padding: 6px 12px;
      border-radius: 4px;
    }

    /* Menu */
    .menu {
      width: 200px;
      background-color: #f2f2f2;
      display: none;
      border-right: 2px solid #333;
    }

    .menu-item {
      padding: 12px;
      border-bottom: 1px solid #ccc;
      cursor: pointer;
    }

    .menu-item:hover {
      background-color: #ddd;
    }

    /* Content */
    .content {
      padding: 20px;
    }

    .status {
      margin-top: 10px;
      font-weight: bold;
      color: green;
    }
  </style>
</head>

<body>

  <!-- Header -->
  <div class="header">
    <div>My Website</div>
    <div class="menu-btn" onclick="toggleMenu()">☰ Menu</div>
  </div>

  <!-- Navigation Menu -->
  <div id="navMenu" class="menu">
    <div class="menu-item"
         onmouseover="hoverItem(this)"
         onmouseout="outItem(this)"
         onclick="selectMenu('Home')">Home</div>

    <div class="menu-item"
         onmouseover="hoverItem(this)"
         onmouseout="outItem(this)"
         onclick="selectMenu('Courses')">Courses</div>

    <div class="menu-item"
         onmouseover="hoverItem(this)"
         onmouseout="outItem(this)"
         onclick="selectMenu('About')">About</div>

    <div class="menu-item"
         onmouseover="hoverItem(this)"
         onmouseout="outItem(this)"
         onclick="selectMenu('Contact')">Contact</div>
  </div>

  <!-- Main Content -->
  <div class="content">
    <h2>Interactive Navigation Menu</h2>
    <p>Click the menu button to open or close the navigation.</p>

    <div class="status" id="status">
      No menu item selected
    </div>
  </div>

  <script>
    // Toggle menu using onclick
    function toggleMenu() {
      let menu = document.getElementById("navMenu");

      if (menu.style.display === "block") {
        menu.style.display = "none";
      } else {
        menu.style.display = "block";
      }
    }

    // Hover effect (onmouseover)
    function hoverItem(item) {
      item.style.backgroundColor = "#bbb";
    }

    // Remove hover effect (onmouseout)
    function outItem(item) {
      item.style.backgroundColor = "#f2f2f2";
    }

    // Menu item click handler
    function selectMenu(name) {
      document.getElementById("status").innerText =
        "Selected Menu: " + name;
    }
  </script>

</body>
</html>
				
			

Dynamic List Click Handler

Handle clicks on list items using event delegation.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Dynamic List Click Handler</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .container {
      width: 450px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    ul {
      padding-left: 20px;
      margin-top: 15px;
    }

    li {
      padding: 8px;
      cursor: pointer;
      border-bottom: 1px solid #ccc;
    }

    li:hover {
      background-color: #f2f2f2;
    }

    button {
      margin-top: 10px;
      padding: 6px 12px;
      cursor: pointer;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
      color: green;
    }
  </style>
</head>

<body>

  <h2>Dynamic List Click Handler</h2>
  <p>Click any list item (even newly added ones).</p>

  <div class="container">

    <button onclick="addItem()">Add New Item</button>

    <ul id="itemList">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>

    <div class="status" id="status">
      No item clicked yet
    </div>

  </div>

  <script>
    let count = 3;

    // Event delegation: single handler on parent <ul>
    document.getElementById("itemList").onclick = function (event) {

      // Check if clicked element is <li>
      if (event.target.tagName === "LI") {

        document.getElementById("status").innerText =
          "Clicked: " + event.target.innerText;

        // Visual feedback
        let items = document.querySelectorAll("#itemList li");
        items.forEach(item => item.style.backgroundColor = "");

        event.target.style.backgroundColor = "#d1ffd1";
      }
    };

    // Dynamically add list items
    function addItem() {
      count++;
      let li = document.createElement("li");
      li.innerText = "Item " + count;
      document.getElementById("itemList").appendChild(li);
    }
  </script>

</body>
</html>
				
			

Image Gallery Hover Preview

Change preview image using mouse events.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Image Gallery Hover Preview</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f5f5f5;
    }

    .gallery-container {
      width: 700px;
      margin-top: 30px;
      padding: 20px;
      border: 2px solid #333;
      background-color: #fff;
    }

    .preview-box {
      width: 100%;
      height: 300px;
      border: 2px solid #555;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #eee;
    }

    .preview-box img {
      max-width: 100%;
      max-height: 100%;
    }

    .thumbs {
      display: flex;
      justify-content: space-between;
    }

    .thumbs img {
      width: 120px;
      height: 80px;
      border: 2px solid #999;
      cursor: pointer;
      transition: transform 0.2s, border 0.2s;
    }

    .thumbs img:hover {
      transform: scale(1.05);
    }

    .active {
      border: 3px solid #007bff;
    }

    .info {
      margin-top: 15px;
      font-weight: bold;
      color: #333;
    }
  </style>
</head>

<body>

  <h2>Image Gallery Hover Preview</h2>
  <p>Hover over any thumbnail to preview the image.</p>

  <div class="gallery-container">

    <!-- Preview Area -->
    <div class="preview-box">
      <img decoding="async" id="preview" src="https://via.placeholder.com/600x300?text=Hover+an+Image"
           alt="Preview Image">
    </div>

    <!-- Thumbnails -->
    <div class="thumbs">
      <img decoding="async" src="https://via.placeholder.com/600x300/ff9999?text=Image+1"
           onmouseover="showPreview(this)"
           onmouseout="resetPreview(this)"
           alt="Image 1">

      <img decoding="async" src="https://via.placeholder.com/600x300/99ff99?text=Image+2"
           onmouseover="showPreview(this)"
           onmouseout="resetPreview(this)"
           alt="Image 2">

      <img decoding="async" src="https://via.placeholder.com/600x300/9999ff?text=Image+3"
           onmouseover="showPreview(this)"
           onmouseout="resetPreview(this)"
           alt="Image 3">

      <img decoding="async" src="https://via.placeholder.com/600x300/ffff99?text=Image+4"
           onmouseover="showPreview(this)"
           onmouseout="resetPreview(this)"
           alt="Image 4">
    </div>

    <div class="info" id="infoText">
      Hover over a thumbnail to see preview
    </div>

  </div>

  <script>
    let defaultImage =
      "https://via.placeholder.com/600x300?text=Hover+an+Image";

    // onmouseover event handler
    function showPreview(img) {
      let preview = document.getElementById("preview");

      preview.src = img.src;
      document.getElementById("infoText").innerText =
        "Previewing: " + img.alt;

      // Remove active class from all thumbnails
      let thumbs = document.querySelectorAll(".thumbs img");
      thumbs.forEach(t => t.classList.remove("active"));

      // Add active class to hovered thumbnail
      img.classList.add("active");
    }

    // onmouseout event handler
    function resetPreview(img) {
      let preview = document.getElementById("preview");

      preview.src = defaultImage;
      document.getElementById("infoText").innerText =
        "Hover over a thumbnail to see preview";

      img.classList.remove("active");
    }
  </script>

</body>
</html>
				
			

Custom Keyboard Shortcuts

Implement shortcuts like Ctrl+S using onkeydown.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Custom Keyboard Shortcuts</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f5f5f5;
    }

    .editor {
      width: 600px;
      padding: 20px;
      border: 2px solid #333;
      background-color: #fff;
      margin-top: 30px;
    }

    textarea {
      width: 100%;
      height: 150px;
      padding: 10px;
      font-size: 15px;
    }

    .shortcuts {
      margin-top: 15px;
      font-size: 14px;
      background-color: #eef;
      padding: 10px;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
      font-size: 16px;
      color: green;
    }
  </style>
</head>

<body onkeydown="handleShortcut(event)">

  <h2>Custom Keyboard Shortcuts</h2>
  <p>Click inside the editor and try the keyboard shortcuts.</p>

  <div class="editor">

    <textarea id="editorText"
              placeholder="Type something here..."></textarea>

    <div class="shortcuts">
      <strong>Available Shortcuts:</strong><br>
      Ctrl + S → Save text<br>
      Ctrl + C → Show copy message<br>
      Ctrl + R → Reset editor<br>
      Esc → Clear status
    </div>

    <div class="status" id="status">
      No shortcut used yet
    </div>

  </div>

  <script>
    // onkeydown event handler
    function handleShortcut(e) {
      let status = document.getElementById("status");
      let editor = document.getElementById("editorText");

      // Ctrl + S (Save)
      if (e.ctrlKey && e.key === "s") {
        e.preventDefault();
        status.innerText = "Text saved (Ctrl + S)";
      }

      // Ctrl + C (Custom copy action)
      else if (e.ctrlKey && e.key === "c") {
        e.preventDefault();
        status.innerText = "Custom copy shortcut triggered (Ctrl + C)";
      }

      // Ctrl + R (Reset editor)
      else if (e.ctrlKey && e.key === "r") {
        e.preventDefault();
        editor.value = "";
        status.innerText = "Editor reset (Ctrl + R)";
      }

      // Escape key
      else if (e.key === "Escape") {
        status.innerText = "Status cleared (Esc)";
      }
    }
  </script>

</body>
</html>
				
			

Scroll Activity Indicator

Show “Scrolling…” status using onscroll.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Scroll Activity Indicator</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      line-height: 1.6;
    }

    /* Fixed status bar */
    .scroll-status {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      padding: 10px;
      background-color: #333;
      color: white;
      text-align: center;
      font-weight: bold;
      display: none;
      z-index: 1000;
    }

    .content {
      padding: 60px 20px;
      max-width: 700px;
      margin: auto;
    }

    .box {
      height: 300px;
      background-color: #f2f2f2;
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #ccc;
    }

    .info-panel {
      position: fixed;
      right: 10px;
      bottom: 10px;
      width: 220px;
      padding: 12px;
      border: 2px solid #333;
      background-color: #fff;
      font-size: 14px;
    }
  </style>
</head>

<body onscroll="trackScroll()">

  <!-- Scroll status -->
  <div class="scroll-status" id="scrollStatus">
    Scrolling...
  </div>

  <!-- Main content -->
  <div class="content">
    <h2>Scroll Activity Indicator</h2>
    <p>Scroll the page to see live scroll activity.</p>

    <div class="box">Content Section 1</div>
    <div class="box">Content Section 2</div>
    <div class="box">Content Section 3</div>
    <div class="box">Content Section 4</div>
    <div class="box">Content Section 5</div>
    <div class="box">Content Section 6</div>
  </div>

  <!-- Info Panel -->
  <div class="info-panel">
    <strong>Scroll Info</strong><br><br>
    Position: <span id="pos">0</span> px<br>
    Direction: <span id="dir">None</span>
  </div>

  <script>
    let lastScroll = 0;
    let scrollTimer;

    // onscroll event handler
    function trackScroll() {
      let currentScroll = window.scrollY;
      let status = document.getElementById("scrollStatus");

      // Show scrolling status
      status.style.display = "block";

      // Detect scroll direction
      if (currentScroll > lastScroll) {
        document.getElementById("dir").innerText = "Down";
      } else {
        document.getElementById("dir").innerText = "Up";
      }

      // Update scroll position
      document.getElementById("pos").innerText = currentScroll;

      lastScroll = currentScroll;

      // Hide status after scrolling stops
      clearTimeout(scrollTimer);
      scrollTimer = setTimeout(() => {
        status.style.display = "none";
      }, 400);
    }
  </script>

</body>
</html>
				
			

Disable Button After Submit

Prevent multiple submissions using onclick.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Disable Button After Submit</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .form-box {
      width: 420px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    label {
      display: block;
      margin-top: 12px;
      font-weight: bold;
    }

    input {
      width: 100%;
      padding: 8px;
      margin-top: 5px;
      font-size: 15px;
    }

    button {
      margin-top: 15px;
      padding: 10px;
      width: 100%;
      font-size: 16px;
      cursor: pointer;
    }

    button:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
      color: green;
    }
  </style>
</head>

<body>

  <h2>Disable Button After Submit</h2>
  <p>Click submit once. Multiple submissions are blocked.</p>

  <div class="form-box">

    <label>Name:</label>
    <input type="text" placeholder="Enter name">

    <label>Email:</label>
    <input type="email" placeholder="Enter email">

    <button id="submitBtn" onclick="submitForm()">
      Submit Form
    </button>

    <div class="status" id="status">
      Waiting for submission
    </div>

  </div>

  <script>
    // onclick event handler
    function submitForm() {
      let btn = document.getElementById("submitBtn");
      let status = document.getElementById("status");

      // Disable button
      btn.disabled = true;
      btn.innerText = "Submitting...";

      // Update status
      status.innerText = "Form submitted successfully";

      // Simulate server processing delay
      setTimeout(() => {
        btn.innerText = "Submitted";
      }, 2000);
    }
  </script>

</body>
</html>
				
			

Modal Popup System

Open/close modal using click and mouse events.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Modal Popup System</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    /* Open button */
    .open-btn {
      padding: 10px 18px;
      font-size: 16px;
      cursor: pointer;
    }

    /* Overlay */
    .overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.6);
      display: none;
      align-items: center;
      justify-content: center;
    }

    /* Modal box */
    .modal {
      width: 400px;
      background-color: #fff;
      padding: 20px;
      border-radius: 6px;
      position: relative;
      animation: zoomIn 0.3s;
    }

    @keyframes zoomIn {
      from { transform: scale(0.8); opacity: 0; }
      to { transform: scale(1); opacity: 1; }
    }

    /* Close button */
    .close-btn {
      position: absolute;
      top: 10px;
      right: 12px;
      font-size: 18px;
      cursor: pointer;
      padding: 4px 8px;
    }

    .close-btn:hover {
      background-color: #eee;
    }

    .modal-footer {
      margin-top: 20px;
      text-align: right;
    }

    .modal-footer button {
      padding: 8px 12px;
      cursor: pointer;
    }

    .modal-footer button:hover {
      background-color: #ddd;
    }
  </style>
</head>

<body>

  <h2>Modal Popup System</h2>
  <p>Click the button below to open the modal.</p>

  <!-- Open Modal Button -->
  <button class="open-btn"
          onclick="openModal()"
          onmouseover="this.style.background='#ddd'"
          onmouseout="this.style.background=''">
    Open Modal
  </button>

  <!-- Overlay + Modal -->
  <div class="overlay" id="overlay" onclick="closeModal()">

    <div class="modal" onclick="event.stopPropagation()">

      <span class="close-btn"
            onclick="closeModal()"
            onmouseover="this.style.color='red'"
            onmouseout="this.style.color='black'">
        ×
      </span>

      <h3>Modal Title</h3>
      <p>
        This is a modal popup window.  
        Click outside the modal or on the close button to close it.
      </p>

      <div class="modal-footer">
        <button onclick="closeModal()">Close</button>
      </div>

    </div>

  </div>

  <script>
    // Open modal
    function openModal() {
      document.getElementById("overlay").style.display = "flex";
    }

    // Close modal
    function closeModal() {
      document.getElementById("overlay").style.display = "none";
    }
  </script>

</body>
</html>
				
			

Simple Drag Detection

Detect drag start/end using mouse events from the PDFs.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Simple Drag Detection</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .drag-area {
      width: 500px;
      height: 300px;
      border: 2px dashed #333;
      margin-top: 30px;
      position: relative;
      background-color: #f9f9f9;
    }

    .box {
      width: 100px;
      height: 100px;
      background-color: #4caf50;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: grab;
      position: absolute;
      top: 100px;
      left: 200px;
      user-select: none;
      font-weight: bold;
    }

    .dragging {
      background-color: #ff9800;
      cursor: grabbing;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
      font-size: 16px;
    }
  </style>
</head>

<body>

  <h2>Simple Drag Detection</h2>
  <p>Click and drag the box inside the area.</p>

  <div class="drag-area"
       onmousemove="dragMove(event)"
       onmouseup="dragEnd()">

    <div id="dragBox"
         class="box"
         onmousedown="dragStart(event)">
      Drag Me
    </div>

  </div>

  <div class="status" id="status">
    Status: Not dragging
  </div>

  <script>
    let isDragging = false;
    let offsetX = 0;
    let offsetY = 0;

    // Drag start (onmousedown)
    function dragStart(e) {
      let box = document.getElementById("dragBox");

      isDragging = true;
      box.classList.add("dragging");

      offsetX = e.clientX - box.offsetLeft;
      offsetY = e.clientY - box.offsetTop;

      document.getElementById("status").innerText =
        "Status: Drag started";
    }

    // Drag move (onmousemove)
    function dragMove(e) {
      if (!isDragging) return;

      let box = document.getElementById("dragBox");

      box.style.left = (e.clientX - offsetX) + "px";
      box.style.top = (e.clientY - offsetY) + "px";

      document.getElementById("status").innerText =
        "Status: Dragging...";
    }

    // Drag end (onmouseup)
    function dragEnd() {
      if (!isDragging) return;

      let box = document.getElementById("dragBox");

      isDragging = false;
      box.classList.remove("dragging");

      document.getElementById("status").innerText =
        "Status: Drag ended";
    }
  </script>

</body>
</html>
				
			

Page Exit Warning

Warn user before leaving page using onunload.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Page Exit Warning</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .box {
      width: 500px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    .info {
      margin-top: 15px;
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .note {
      margin-top: 10px;
      font-size: 14px;
      color: #555;
    }
  </style>
</head>

<body onunload="pageExit()">

  <h2>Page Exit Warning</h2>
  <p>Try refreshing the page or closing the tab.</p>

  <div class="box">
    <div class="info" id="status">
      Page is active
    </div>

    <div class="note">
      This example uses <strong>onunload</strong> as described in the syllabus PDFs.
    </div>
  </div>

  <script>
    // onunload event handler
    function pageExit() {
      // This message may not always be shown due to browser security
      alert("You are leaving this page.");
    }
  </script>

</body>
</html>
				
			

Student Registration Form

Uses onfocus, onblur, onchange, onsubmit.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Student Registration Form</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .form-box {
      width: 450px;
      padding: 20px;
      border: 2px solid #333;
      margin-top: 30px;
    }

    label {
      display: block;
      margin-top: 12px;
      font-weight: bold;
    }

    input, select {
      width: 100%;
      padding: 8px;
      margin-top: 5px;
      font-size: 15px;
    }

    .error {
      font-size: 13px;
      color: red;
    }

    .info {
      margin-top: 10px;
      font-size: 14px;
      color: #555;
    }

    button {
      margin-top: 15px;
      padding: 10px;
      width: 100%;
      font-size: 16px;
      cursor: pointer;
    }

    .success {
      margin-top: 15px;
      font-weight: bold;
      color: green;
    }
  </style>
</head>

<body>

  <h2>Student Registration Form</h2>
  <p>Please fill all details carefully.</p>

  <div class="form-box">

    <form onsubmit="return submitForm()">

      <!-- Name -->
      <label>Student Name</label>
      <input type="text" id="name"
             onfocus="highlight(this)"
             onblur="validateName()">
      <div class="error" id="nameError"></div>

      <!-- Email -->
      <label>Email</label>
      <input type="text" id="email"
             onfocus="highlight(this)"
             onblur="validateEmail()">
      <div class="error" id="emailError"></div>

      <!-- Course -->
      <label>Select Course</label>
      <select id="course"
              onfocus="highlight(this)"
              onchange="courseChanged()">
        <option value="">-- Select Course --</option>
        <option>Web Development</option>
        <option>Graphic Design</option>
        <option>Data Analytics</option>
      </select>
      <div class="info" id="courseInfo"></div>

      <!-- Mobile -->
      <label>Mobile Number</label>
      <input type="text" id="mobile"
             onfocus="highlight(this)"
             onblur="validateMobile()">
      <div class="error" id="mobileError"></div>

      <button type="submit">Register</button>

    </form>

    <div class="success" id="successMsg"></div>

  </div>

  <script>
    // onfocus event – highlight field
    function highlight(field) {
      field.style.backgroundColor = "#ffffcc";
      field.style.border = "2px solid green";
    }

    // onblur – validate name
    function validateName() {
      let name = document.getElementById("name").value;
      let error = document.getElementById("nameError");

      if (name.trim() === "") {
        error.innerText = "Name is required";
        return false;
      } else {
        error.innerText = "";
        return true;
      }
    }

    // onblur – validate email
    function validateEmail() {
      let email = document.getElementById("email").value;
      let error = document.getElementById("emailError");

      if (!email.includes("@") || !email.includes(".")) {
        error.innerText = "Enter a valid email address";
        return false;
      } else {
        error.innerText = "";
        return true;
      }
    }

    // onchange – course selection
    function courseChanged() {
      let course = document.getElementById("course").value;
      let info = document.getElementById("courseInfo");

      if (course !== "") {
        info.innerText = "You selected: " + course;
      } else {
        info.innerText = "";
      }
    }

    // onblur – validate mobile
    function validateMobile() {
      let mobile = document.getElementById("mobile").value;
      let error = document.getElementById("mobileError");

      if (mobile.length !== 10 || isNaN(mobile)) {
        error.innerText = "Enter a valid 10-digit mobile number";
        return false;
      } else {
        error.innerText = "";
        return true;
      }
    }

    // onsubmit – final validation
    function submitForm() {
      let valid =
        validateName() &&
        validateEmail() &&
        validateMobile() &&
        document.getElementById("course").value !== "";

      if (!valid) {
        alert("Please fix errors before submitting");
        return false;
      }

      document.getElementById("successMsg").innerText =
        "Registration successful!";
      return false; // prevent actual submission for demo
    }
  </script>

</body>
</html>
				
			

Interactive Quiz App

Uses click, keyboard, and submit events.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Interactive Quiz App</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
    }

    .quiz-container {
      width: 650px;
      margin: 30px auto;
      padding: 25px;
      background-color: #fff;
      border: 2px solid #333;
    }

    .question {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 15px;
    }

    .option {
      padding: 10px;
      border: 1px solid #999;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .option:hover {
      background-color: #eef;
    }

    .selected {
      background-color: #cce5ff;
      border-color: #007bff;
    }

    .controls {
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
    }

    button {
      padding: 8px 14px;
      font-size: 15px;
      cursor: pointer;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
    }

    .instructions {
      margin-bottom: 15px;
      font-size: 14px;
      background-color: #f0f8ff;
      padding: 10px;
    }
  </style>
</head>

<body onkeydown="handleKey(event)">

  <div class="quiz-container">

    <h2>Interactive Quiz App</h2>

    <div class="instructions">
      👉 Click options or press <strong>1-4</strong> to select<br>
      👉 Press <strong>Enter</strong> to go to next question
    </div>

    <form onsubmit="return submitQuiz()">

      <div class="question" id="questionText"></div>

      <div class="option" onclick="selectOption(0)" id="opt0"></div>
      <div class="option" onclick="selectOption(1)" id="opt1"></div>
      <div class="option" onclick="selectOption(2)" id="opt2"></div>
      <div class="option" onclick="selectOption(3)" id="opt3"></div>

      <div class="controls">
        <button type="button" onclick="nextQuestion()">Next</button>
        <button type="submit">Submit Quiz</button>
      </div>

    </form>

    <div class="status" id="status">
      Question 1 of 3
    </div>

  </div>

  <script>
    const questions = [
      {
        q: "Which language is used for web page structure?",
        options: ["CSS", "JavaScript", "HTML", "Python"],
        answer: 2
      },
      {
        q: "Which event triggers when a key is pressed?",
        options: ["onclick", "onkeyup", "onkeydown", "onsubmit"],
        answer: 2
      },
      {
        q: "Which event is used to submit a form?",
        options: ["onblur", "onchange", "onclick", "onsubmit"],
        answer: 3
      }
    ];

    let current = 0;
    let selected = null;
    let score = 0;

    function loadQuestion() {
      let q = questions[current];
      document.getElementById("questionText").innerText = q.q;

      q.options.forEach((opt, i) => {
        document.getElementById("opt" + i).innerText =
          (i + 1) + ". " + opt;
        document.getElementById("opt" + i).classList.remove("selected");
      });

      selected = null;
      document.getElementById("status").innerText =
        "Question " + (current + 1) + " of " + questions.length;
    }

    function selectOption(index) {
      selected = index;

      document.querySelectorAll(".option").forEach(opt =>
        opt.classList.remove("selected")
      );

      document.getElementById("opt" + index).classList.add("selected");
    }

    function nextQuestion() {
      if (selected === null) {
        alert("Please select an option");
        return;
      }

      if (selected === questions[current].answer) {
        score++;
      }

      current++;

      if (current < questions.length) {
        loadQuestion();
      } else {
        submitQuiz();
      }
    }

    function handleKey(e) {
      if (e.key >= "1" && e.key <= "4") {
        selectOption(parseInt(e.key) - 1);
      }

      if (e.key === "Enter") {
        e.preventDefault();
        nextQuestion();
      }
    }

    function submitQuiz() {
      if (current < questions.length && selected !== null) {
        if (selected === questions[current].answer) {
          score++;
        }
      }

      document.querySelector(".quiz-container").innerHTML =
        "<h2>Quiz Completed</h2>" +
        "<p><strong>Score:</strong> " + score +
        " / " + questions.length + "</p>";

      return false;
    }

    loadQuestion();
  </script>

</body>
</html>
				
			

Live Search Filter

Filter list items using onkeyup.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Live Search Filter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
    }

    .search-container {
      width: 500px;
      margin: 30px auto;
      padding: 20px;
      background-color: #fff;
      border: 2px solid #333;
    }

    input {
      width: 100%;
      padding: 10px;
      font-size: 16px;
      margin-bottom: 15px;
    }

    ul {
      list-style: none;
      padding: 0;
    }

    li {
      padding: 10px;
      border-bottom: 1px solid #ccc;
    }

    li span {
      background-color: yellow;
      font-weight: bold;
    }

    .info {
      margin-top: 10px;
      font-size: 14px;
      font-weight: bold;
      color: #333;
    }

    .no-result {
      color: red;
      font-weight: bold;
      display: none;
      margin-top: 10px;
    }
  </style>
</head>

<body>

  <div class="search-container">

    <h2>Live Search Filter</h2>
    <p>Type to search courses in real time.</p>

    <!-- Search Input -->
    <input type="text"
           id="searchBox"
           placeholder="Search course..."
           onkeyup="filterList()">

    <!-- List -->
    <ul id="itemList">
      <li>Web Development</li>
      <li>Graphic Design</li>
      <li>Data Analytics</li>
      <li>Java Programming</li>
      <li>Python Programming</li>
      <li>Digital Marketing</li>
      <li>UI UX Design</li>
      <li>Cyber Security</li>
    </ul>

    <div class="info" id="count">
      Showing 8 results
    </div>

    <div class="no-result" id="noResult">
      No matching results found
    </div>

  </div>

  <script>
    // onkeyup event handler
    function filterList() {
      let input = document.getElementById("searchBox").value.toLowerCase();
      let items = document.querySelectorAll("#itemList li");
      let count = 0;

      items.forEach(item => {
        let text = item.innerText;
        let lowerText = text.toLowerCase();

        if (lowerText.includes(input)) {
          item.style.display = "block";
          count++;

          // Highlight matching text
          if (input !== "") {
            let regex = new RegExp("(" + input + ")", "gi");
            item.innerHTML = text.replace(regex, "<span>$1</span>");
          } else {
            item.innerHTML = text;
          }
        } else {
          item.style.display = "none";
        }
      });

      document.getElementById("count").innerText =
        "Showing " + count + " result(s)";

      document.getElementById("noResult").style.display =
        count === 0 ? "block" : "none";
    }
  </script>

</body>
</html>
				
			

Theme Switcher Tool

Toggle light/dark mode using events.

				
					<!DOCTYPE html>
<html>
<head>
  <title>Theme Switcher Tool</title>
  <style>
    :root {
      --bg: #ffffff;
      --text: #222222;
      --card: #f2f2f2;
      --border: #333333;
    }

    body.dark {
      --bg: #121212;
      --text: #eaeaea;
      --card: #1e1e1e;
      --border: #888888;
    }

    body {
      font-family: Arial, sans-serif;
      background-color: var(--bg);
      color: var(--text);
      margin: 0;
      transition: background-color 0.3s, color 0.3s;
    }

    .container {
      width: 600px;
      margin: 30px auto;
      padding: 20px;
      border: 2px solid var(--border);
      background-color: var(--card);
      transition: background-color 0.3s, border 0.3s;
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .toggle-btn {
      padding: 8px 14px;
      font-size: 15px;
      cursor: pointer;
      border: 1px solid var(--border);
      background-color: transparent;
      color: var(--text);
    }

    .toggle-btn:hover {
      opacity: 0.9;
    }

    .status {
      margin-top: 15px;
      font-weight: bold;
    }

    .hint {
      margin-top: 10px;
      font-size: 14px;
      opacity: 0.8;
    }
  </style>
</head>

<body onkeydown="handleKey(event)">

  <div class="container">

    <div class="header">
      <h2>Theme Switcher Tool</h2>
      <button class="toggle-btn" onclick="toggleTheme()">
        Toggle Theme
      </button>
    </div>

    <p>
      This tool allows users to switch between Light and Dark mode
      using events, just like modern applications.
    </p>

    <div class="status" id="status">
      Current Theme: Light
    </div>

    <div class="hint">
      Tip: Press <strong>D</strong> on keyboard to toggle theme
    </div>

  </div>

  <script>
    // Apply saved theme on load
    (function initTheme() {
      let savedTheme = localStorage.getItem("theme");
      if (savedTheme === "dark") {
        document.body.classList.add("dark");
        updateStatus();
      }
    })();

    // onclick event – toggle theme
    function toggleTheme() {
      document.body.classList.toggle("dark");

      let isDark = document.body.classList.contains("dark");
      localStorage.setItem("theme", isDark ? "dark" : "light");

      updateStatus();
    }

    // onkeydown event – keyboard shortcut
    function handleKey(e) {
      if (e.key === "d" || e.key === "D") {
        toggleTheme();
      }
    }

    // Update UI status text
    function updateStatus() {
      let status = document.getElementById("status");
      let isDark = document.body.classList.contains("dark");

      status.innerText =
        "Current Theme: " + (isDark ? "Dark" : "Light");
    }
  </script>

</body>
</html>
				
			

Event Playground Page

One page demonstrating all major events learned.

				
					<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Event Playground</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0 20px;
      line-height: 1.6;
    }

    h2 {
      background: #333;
      color: #fff;
      padding: 10px;
    }

    .section {
      border: 2px solid #333;
      padding: 15px;
      margin-bottom: 25px;
    }

    button {
      padding: 6px 12px;
      cursor: pointer;
      margin-top: 5px;
    }

    input, select {
      padding: 6px;
      width: 250px;
      margin-top: 5px;
    }

    .box {
      width: 200px;
      height: 100px;
      border: 2px solid #333;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 10px;
      user-select: none;
    }

    .log {
      font-weight: bold;
      margin-top: 8px;
    }
  </style>
</head>

<body onload="pageLoaded()" onscroll="scrolling()" onkeydown="keyDown(event)" onkeyup="keyUp(event)">

<h1>JavaScript Event Playground</h1>
<p>Interact with each section to observe different JavaScript events.</p>

<!-- CLICK EVENTS -->
<h2>1. Click Events</h2>
<div class="section">
  <button onclick="alert('Button clicked')">onclick</button>
  <button ondblclick="alert('Button double clicked')">ondblclick</button>
</div>

<!-- MOUSE EVENTS -->
<h2>2. Mouse Events</h2>
<div class="section">
  <div class="box"
       onmouseover="this.style.background='lightgreen'"
       onmouseout="this.style.background=''"
       onmousedown="this.innerText='Mouse Down'"
       onmouseup="this.innerText='Mouse Up'">
    Hover / Click Me
  </div>
</div>

<!-- KEYBOARD EVENTS -->
<h2>3. Keyboard Events</h2>
<div class="section">
  <input type="text" placeholder="Type here">
  <div class="log" id="keyLog">Key activity will appear here</div>
</div>

<!-- FORM EVENTS -->
<h2>4. Form Events</h2>
<div class="section">
  <form onsubmit="return submitForm()" onreset="resetForm()">

    <input type="text"
           placeholder="Name"
           onfocus="focusField(this)"
           onblur="blurField(this)">
    <br><br>

    <select onchange="courseChange(this.value)">
      <option value="">Select Course</option>
      <option>Web Development</option>
      <option>Graphic Design</option>
    </select>

    <br><br>
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>

  </form>

  <div class="log" id="formLog"></div>
</div>

<!-- SELECT EVENT -->
<h2>5. Text Selection Event</h2>
<div class="section">
  <input type="text"
         value="Select some text here"
         onselect="document.getElementById('selectLog').innerText='Text selected'">
  <div class="log" id="selectLog"></div>
</div>

<!-- IMAGE ERROR -->
<h2>6. Image Error Event</h2>
<div class="section">
  <img decoding="async" src="wrong-image.png"
       width="150"
       onerror="this.alt='Image not found'">
</div>

<!-- WINDOW EVENTS -->
<h2>7. Window Events</h2>
<div class="section">
  <div class="log" id="windowLog">
    Resize or scroll the page
  </div>
</div>

<script>
  function pageLoaded() {
    console.log("Page Loaded");
  }

  function scrolling() {
    document.getElementById("windowLog").innerText = "Scrolling page...";
  }

  function keyDown(e) {
    document.getElementById("keyLog").innerText =
      "Key Down: " + e.key;
  }

  function keyUp(e) {
    document.getElementById("keyLog").innerText =
      "Key Up: " + e.key;
  }

  function focusField(el) {
    el.style.background = "#ffffcc";
  }

  function blurField(el) {
    el.style.background = "";
  }

  function courseChange(val) {
    document.getElementById("formLog").innerText =
      "Course selected: " + val;
  }

  function submitForm() {
    document.getElementById("formLog").innerText =
      "Form submitted";
    return false;
  }

  function resetForm() {
    document.getElementById("formLog").innerText =
      "Form reset";
  }
</script>

</body>
</html>