\n\n\n\n```"}}}Back to the 2019 paper

Module III: Basics of Web Programming

20197m

What are events? Explain the events used in JavaScript with the help of examples.

Worked SolutionAI Assisted

Answer: Events and Event Handling in JavaScript

1. What are Events in JavaScript?

In JavaScript, an Event is an action or occurrence recognized by software, initiated either by the user (e.g., clicking a button, pressing a key, moving the mouse) or by the browser (e.g., page loading, network error).

JavaScript uses Event Listeners / Handlers to execute specific functions whenever a targeted event occurs on a DOM element.

[ User Action: Click Button ] ---> [ Event Object Created: 'click' ] ---> [ Event Listener Dispatches Callback ] ---> [ DOM / UI Updated ]

2. Three Ways to Register Event Handlers

  1. Inline HTML Attributes:
    <button onclick="alert('Button Clicked!')">Click Me</button>
    
  2. DOM Object Property:
    const btn = document.getElementById("myBtn");
    btn.onclick = function() { console.log("Clicked"); };
    
  3. W3C Standard addEventListener() (Recommended):
    const btn = document.getElementById("myBtn");
    btn.addEventListener("click", (event) => {
        console.log("Button clicked at coordinates: " + event.clientX + ", " + event.clientY);
    });
    

3. Major Categories of JavaScript Events

A. Mouse Events

Event Trigger Condition Code Example
click User clicks on an element btn.addEventListener('click', handleClick)
dblclick User double-clicks an element box.addEventListener('dblclick', handleDoubleClick)
mouseover Mouse pointer enters element boundaries card.addEventListener('mouseover', highlight)
mouseout Mouse pointer leaves element boundaries card.addEventListener('mouseout', unhighlight)
mousemove Mouse pointer moves over an element canvas.addEventListener('mousemove', draw)

B. Keyboard Events

Event Trigger Condition Code Example
keydown Key is pressed down input.addEventListener('keydown', (e) => console.log(e.key))
keyup Key is released input.addEventListener('keyup', validate)

C. Form Events

Event Trigger Condition Code Example
submit Form is submitted (can intercept via e.preventDefault()) form.addEventListener('submit', validateForm)
change Value of an input/select element has changed and lost focus select.addEventListener('change', updateSelection)
focus Element receives focus input.addEventListener('focus', showHint)
blur Element loses focus input.addEventListener('blur', hideHint)
input Value changes in real-time input.addEventListener('input', updateCharCount)

D. Window / Document Lifecycle Events

Event Trigger Condition Code Example
DOMContentLoaded HTML document is fully parsed into DOM (without waiting for images/stylesheets) document.addEventListener('DOMContentLoaded', init)
load Entire page including all stylesheets, scripts, and images is fully loaded window.addEventListener('load', startApp)
resize Browser window viewport is resized window.addEventListener('resize', handleResize)
scroll User scrolls the document window.addEventListener('scroll', checkScrollPosition)

4. Comprehensive Interactive Demonstration

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Events Demo</title>
</head>
<body>

  <h2>JavaScript Event Handling Demo</h2>
  
  <!-- Mouse Event -->
  <button id="alertBtn">Click Me (Mouse Event)</button>

  <!-- Keyboard Event -->
  <p>Type below to see live character count (Keyboard Event):</p>
  <input type="text" id="textInput" placeholder="Type something...">
  <span id="charCount">0 characters</span>

  <!-- Form Event -->
  <form id="sampleForm" style="margin-top:20px;">
    <input type="text" id="username" placeholder="Username" required>
    <button type="submit">Submit Form</button>
  </form>
  <p id="statusMsg"></p>

  <script>
    // 1. Mouse Event
    document.getElementById("alertBtn").addEventListener("click", () => {
        alert("Mouse Click Event Triggered!");
    });

    // 2. Keyboard & Input Event
    const textInput = document.getElementById("textInput");
    const charCount = document.getElementById("charCount");
    textInput.addEventListener("input", () => {
        charCount.innerText = textInput.value.length + " characters";
    });

    // 3. Form Submit Event with preventDefault()
    document.getElementById("sampleForm").addEventListener("submit", (e) => {
        e.preventDefault(); // Prevents page reload
        const user = document.getElementById("username").value;
        document.getElementById("statusMsg").innerText = "Form submitted for: " + user;
    });
  </script>

</body>
</html>

Similar questions