Հայերեն Русский

Introduction to Event Handling in JavaScript

What are Events?

In the context of web development, events are actions or occurrences that happen within the browser window or on a web page, which the system can detect and provide you with the opportunity to respond. These can include user interactions like clicks, key presses, or more complex occurrences like the loading or unloading of a web page.

Events are central to creating interactive applications in JavaScript. By responding to these events, developers can craft dynamic responses that enhance the user experience.

Event Listeners

To react to these events, JavaScript provides a mechanism called event listeners. An event listener "listens" for a specific event happening, such as a button being clicked or a key being pressed, and then triggers a function, known as an event handler, in response.

Syntax of addEventListener:

element.addEventListener(event, function, useCapture);
    

Example of Adding an Event Listener:

document.getElementById("myButton").addEventListener("click", function() {
        alert("Button clicked!");
    });
    

This code snippet adds an event listener to an element with the ID myButton. When the button is clicked, it triggers an alert.

Types of Events

Events in JavaScript can be broadly categorized into several types based on the kind of interaction they represent:

Practical Examples

Adding Event Listeners to Buttons and Forms:

Hands-On Exercise

For the practical exercise, students will create an interactive form that reacts to user inputs in real-time.

Exercise Setup:

  1. Create a Simple Form in HTML:

    <form id="liveForm">
            <label for="nameInput">Enter your name:</label>
            <input type="text" id="nameInput" />
            <p id="livePreview"></p>
            <button type="submit">Submit</button>
        </form>
        
  2. Add Event Listeners for Live Preview:

    document.getElementById("nameInput").addEventListener("input", function() {
            let preview = document.getElementById("livePreview");
            preview.innerText = "Preview: " + this.value;
        });
        

In this exercise, the form includes an input where users can type their name. As the user types, the input event triggers updating a paragraph element (livePreview) with a preview of the input, demonstrating how event handling can be used to create a responsive interface.

Advanced Event Handling Techniques

Event Propagation: Bubbling and Capturing

Event propagation is a mechanism that defines how events propagate or travel through the DOM tree to arrive at their target element and potentially bubble up or capture down after reaching the target.

// Example of setting up capturing
    document.getElementById("parent").addEventListener("click", function() {
        console.log("Parent clicked - capturing phase");
    }, true); // Capturing is enabled
    

Understanding these mechanisms is crucial when designing complex interactive web applications to manage how events are handled and propagated through the DOM tree.

Preventing Default Actions

Many DOM elements have default behaviors that can be executed on specific events. For example, clicking a submit button in a form element typically refreshes the page. You can prevent these default actions using event.preventDefault() within an event handler.

This is particularly useful in form handling where you want to have complete control over the submission process, possibly to perform validation, make an AJAX request, or manipulate data before sending it to a server.

Using this in Events

In the context of an event handler, the this keyword refers to the element on which the event handler is currently executing. This is extremely helpful when you want to manipulate the element that received the event or access its properties.

document.getElementById("myButton").addEventListener("click", function() {
        console.log(this.textContent); // `this` refers to the button
        this.textContent = "Clicked"; // Changes the button text to 'Clicked'
    });
    

Exercise: Handling Form Submission with Event Propagation Control

Objective: Implement an exercise where students need to stop the propagation of an event and prevent the default behavior of a form submission to handle it using JavaScript.

Setup:

  1. HTML Structure:

    <form id="signupForm">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <button type="submit">Sign Up</button>
        </form>
        
  2. JavaScript:

    document.getElementById("signupForm").addEventListener("submit", function(event) {
            event.preventDefault(); // Prevent default form submission
            event.stopPropagation(); // Stop the event from bubbling up
            let username = document.getElementById("username").value;
            console.log("Signing up user:", username);
            // Additional code to process the username
        });
        

In this exercise, students will attach an event listener to a form that stops the form from submitting in the traditional way and prevents the event from bubbling up the DOM. This approach allows the form to be processed entirely within JavaScript, offering more control over data handling and interaction flow. This practice solidifies understanding of event handling, propagation, and default action prevention in real-world scenarios.

Introduction to Web Storage

Overview of Web Storage

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies. The two mechanisms within Web Storage are localStorage and sessionStorage, each serving different needs and providing ways to persist data on the client's browser.

Features of Web Storage:

localStorage vs sessionStorage

  1. localStorage:

  2. sessionStorage:

Setting, Getting, and Removing Items

Both localStorage and sessionStorage expose the same methods, providing a simple API for managing stored data.

Practical Exercise: Building a Theme Preference Application

Objective: Create a simple application that allows users to choose a theme color for the website, which will persist across sessions using localStorage.

Steps:

  1. HTML Setup:

    <label>Select your theme color:</label>
        <select id="themeSelector">
            <option value="light">Light</option>
            <option value="dark">Dark</option>
        </select>
        <button onclick="saveTheme()">Save Theme</button>
        
  2. JavaScript Implementation:

    function saveTheme() {
            let theme = document.getElementById("themeSelector").value;
            localStorage.setItem("theme", theme);
        }
    
        function loadTheme() {
            let theme = localStorage.getItem("theme");
            if (theme) {
                document.body.className = theme;  // Assuming CSS classes for themes exist
                document.getElementById("themeSelector").value = theme;
            }
        }
    
        window.onload = loadTheme;  // Load the theme when the document loads
        

Learning Outcomes:

This exercise not only reinforces understanding of the Web Storage API but also illustrates its practical use in real-world web applications, such as customizing and remembering user settings.

Combining Event Handling with Web Storage

Interactive Application Example: To-Do List

One of the most illustrative examples of combining event handling with Web Storage is creating a to-do list application. This application will allow users to add tasks, mark them as completed, and persist the state of the list across browser sessions using localStorage.

Application Features:

  1. Add Tasks: Users can enter tasks into an input field and add them to the list by pressing a button or hitting enter.
  2. Mark Tasks as Completed: Users can click on tasks to toggle their completion status.
  3. Persistence: The state of the to-do list is saved to localStorage, so it remains intact even after the browser or tab is closed and reopened.

HTML Structure:

<div id="todoApp">
        <input type="text" id="newTask" placeholder="Add a new task" />
        <button onclick="addTask()">Add Task</button>
        <ul id="taskList"></ul>
    </div>
    

CSS for Completed Tasks (for visual feedback):

.completed {
        text-decoration: line-through;
    }
    

JavaScript for Event Handling and Local Storage:

function loadTasks() {
        let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
        let taskList = document.getElementById('taskList');
        taskList.innerHTML = ''; // Clear existing tasks in the DOM
        tasks.forEach((task, index) => {
            let li = document.createElement('li');
            li.textContent = task.description;
            li.className = task.completed ? 'completed' : '';
            li.addEventListener('click', () => toggleTask(index));
            taskList.appendChild(li);
        });
    }

    function addTask() {
        let newTaskInput = document.getElementById('newTask');
        let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
        if (newTaskInput.value) {
            tasks.push({ description: newTaskInput.value, completed: false });
            localStorage.setItem('tasks', JSON.stringify(tasks));
            newTaskInput.value = ''; // Clear input field
            loadTasks(); // Refresh the list
        }
    }

    function toggleTask(index) {
        let tasks = JSON.parse(localStorage.getItem('tasks'));
        tasks[index].completed = !tasks[index].completed;
        localStorage.setItem('tasks', JSON.stringify(tasks));
        loadTasks();
    }

    window.onload = loadTasks; // Load tasks when the document is ready
    

Exercise: Enhance the Interactive Form

Students will enhance an interactive form they created earlier by incorporating functionality that saves user inputs into localStorage. This will allow the data to be retrieved when the form is reloaded.

Features to Implement:

  1. Save Input Data: Every time a user modifies a field in the form, save the data to localStorage.
  2. Retrieve Data on Load: When the form is loaded (e.g., when the page is refreshed), populate the form fields with the data stored in localStorage.

Example Scenario: Suppose the form collects user preferences, such as favorite color and email address.

HTML:

<form id="preferenceForm">
        <input type="email" id="email" placeholder="Enter your email">
        <input type="color" id="favoriteColor" title="Choose your favorite color">
        <button type="submit">Save Preferences</button>
    </form>
    

JavaScript:

document.getElementById('preferenceForm').addEventListener('change', function(event) {
        localStorage.setItem(event.target.id, event.target.value);
    });

    function loadPreferences() {
        document.getElementById('email').value = localStorage.getItem('email') || '';
        document.getElementById('favoriteColor').value = localStorage.getItem('favoriteColor') || '#ffffff'; // Default to white
    }

    window.onload = loadPreferences;
    

This exercise will help students understand how to effectively combine event handling with localStorage to create dynamic, user-friendly web applications that remember user inputs across sessions, enhancing the user experience significantly.