Paramclasses Academy - Blog

Tutorials Details

jQuery Events with Practical Examples

jQuery Events with Practical Examples

October 12, 2026

Introduction to jQuery Events

jQuery events allow a website to respond to user actions. These actions include clicking a button, typing in an input field, selecting an option, moving the mouse over an element, or submitting a form.

For example, when a customer clicks the “Book Now” button on a hotel website, the website can display a confirmation message or open a booking form. Similarly, a contact form can display a message when the user submits incomplete information.

In this tutorial, you will learn how to handle common jQuery events, understand their syntax, and implement them in practical web applications.

1. What Are jQuery Events?

An event is an action that occurs in a browser, usually because of user interaction or a change in the page.

Common examples include:

  • Clicking a button.

  • Double-clicking an element.

  • Moving the mouse over a product card.

  • Typing in a search field.

  • Changing a dropdown selection.

  • Submitting a contact form.

jQuery provides methods for registering event handlers, which are functions that run when a particular event occurs.

Basic Syntax

$(selector).on("event", function () {
    // Code to execute when the event occurs
});

For example:

$("#myButton").on("click", function () {
    alert("Button clicked!");
});

When the user clicks the element with the ID myButton, the message appears.

2. Click Event in jQuery

The click event runs a function when an element is clicked.

Example: Button Click

<button type="button" id="welcomeBtn">Click Me</button>

<script>
$(function () {
    $("#welcomeBtn").on("click", function () {
        alert("Welcome to our website!");
    });
});
</script>

How It Works

  1. #welcomeBtn selects the button.

  2. .on("click", ...) registers a click handler.

  3. When the button is clicked, the function runs.

Practical application: Display a welcome message, open a modal, reveal additional information, or respond to a booking button.

3. Double-Click Event in jQuery

The dblclick event runs when an element is double-clicked.

Example

<p id="productName">Deluxe Room</p>

<script>
$(function () {
    $("#productName").on("dblclick", function () {
        $(this).css("color", "blue");
    });
});
</script>

Double-clicking the room name changes its text color to blue.

Practical application: You can use double-click interactions in specialized interfaces, although important website actions should generally use standard single-click controls for better usability.

4. Mouse Events in jQuery

Mouse events let you respond to pointer interactions.

Mouseenter Event

The mouseenter event occurs when the pointer enters an element.

<div id="roomCard">Deluxe Room</div>

<script>
$(function () {
    $("#roomCard").on("mouseenter", function () {
        $(this).css("background-color", "#e6f4ea");
    });
});
</script>

When the pointer enters the room card, its background color changes.

Mouseleave Event

The mouseleave event occurs when the pointer leaves an element.

$("#roomCard").on("mouseleave", function () {
    $(this).css("background-color", "white");
});

This resets the background color when the pointer leaves the card.

Practical application: Add hover effects to room cards, product listings, menus, and other interface elements. For touch devices, make sure important information is not available only on hover.

5. Keyboard Events in jQuery

Keyboard events help detect actions such as pressing or releasing a key.

Common keyboard events include:

  • keydown: A key is pressed.

  • keyup: A key is released.

Example: Live Character Counter

<textarea id="message" maxlength="100"
          placeholder="Write your message"></textarea>

<p>Characters: <span id="count">0</span>/100</p>

<script>
$(function () {
    $("#message").on("input", function () {
        $("#count").text($(this).val().length);
    });
});
</script>

As the user types a message, the character count updates automatically.

This example uses the input event because it responds to typing, pasting, and other changes to the field's value.

Practical application: Message forms, feedback forms, search boxes, and comment sections.

6. Change Event in jQuery

The change event runs when a form control's value changes and the change is committed. For text fields, this commonly occurs when the field loses focus after its value has changed.

Example: Room Type Selection

<label for="roomType">Choose Room Type:</label>

<select id="roomType">
    <option value="">Select a room</option>
    <option value="deluxe">Deluxe Room</option>
    <option value="family">Family Room</option>
    <option value="suite">Suite Room</option>
</select>

<p id="selectedRoom">Your selected room will appear here.</p>

<script>
$(function () {
    $("#roomType").on("change", function () {
        const room = $(this).val();

        if (room === "") {
            $("#selectedRoom").text("Please select a room.");
        } else {
            $("#selectedRoom").text("Selected room: " + room);
        }
    });
});
</script>

When the visitor selects a room type, the page displays the selected value.

Practical application: Room selection, country dropdowns, category filters, and settings forms.

7. Input Event in jQuery

The input event responds immediately when the value of an input or textarea changes.

Example: Live Search Preview

<input type="text" id="search"
       placeholder="Search for a room">

<p id="searchText">Your search will appear here.</p>

<script>
$(function () {
    $("#search").on("input", function () {
        const query = $(this).val().trim();

        $("#searchText").text(
            query ? "Searching for: " + query : "Enter a search term."
        );
    });
});
</script>

This example displays the search term as the user types. It does not search a database; a real search feature would need to filter data or send a request to a server.

8. Submit Event in jQuery

The submit event lets you handle a form submission.

Example: Contact Form Validation

<form id="contactForm">
    <label for="name">Your Name</label>
    <input type="text" id="name" name="name">

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

    <p id="formMessage" aria-live="polite"></p>
</form>

<script>
$(function () {
    $("#contactForm").on("submit", function (event) {
        event.preventDefault();

        const name = $("#name").val().trim();

        if (name === "") {
            $("#formMessage").text("Please enter your name.");
        } else {
            $("#formMessage").text("Form validation successful.");
        }
    });
});
</script>

How It Works

  • .on("submit", ...) registers the form handler.

  • event.preventDefault() prevents the browser's default form submission.

  • .val() retrieves the field value.

  • .trim() removes leading and trailing whitespace.

  • .text() displays the result.

This is only client-side validation. A real application must validate input on the server before saving it or taking other important actions.

9. Focus and Blur Events in jQuery

The focus event occurs when an input receives focus. The blur event occurs when it loses focus.

Example: Highlight an Input Field

<input type="text" id="guestName" placeholder="Enter guest name">

<script>
$(function () {
    $("#guestName").on("focus", function () {
        $(this).css("border", "2px solid #0d6efd");
    });

    $("#guestName").on("blur", function () {
        $(this).css("border", "1px solid #ccc");
    });
});
</script>

The input border changes when the user selects the field and returns to its normal style when focus moves elsewhere.

Practical application: Improve form usability by making the active input field easier to identify.

10. Using the on() Method

The on() method is a flexible way to attach event handlers in jQuery.

Example

$("#saveBtn").on("click", function () {
    $("#status").text("Changes saved.");
});

You can also attach a handler for multiple event types:

$("#roomCard").on("mouseenter mouseleave", function () {
    $(this).toggleClass("highlight");
});

Here, the class is toggled on both pointer entry and pointer exit.

For more complex interfaces, consider whether the class should be added and removed separately to make the intended behavior clearer.

11. Removing an Event Handler with off()

The off() method removes event handlers previously attached using jQuery.

Example

<button id="testBtn">Click Me</button>
<button id="removeHandler">Disable Button Action</button>

<script>
$(function () {
    function showMessage() {
        alert("Button clicked!");
    }

    $("#testBtn").on("click", showMessage);

    $("#removeHandler").on("click", function () {
        $("#testBtn").off("click", showMessage);
    });
});
</script>

After clicking “Disable Button Action”, the original click handler is removed from the first button.

Practical application: Enable or disable certain interface interactions when application state changes.

12. Event Delegation in jQuery

Event delegation lets a parent element handle events from its matching descendants. It is particularly useful when elements are added dynamically after the page loads.

Example: Dynamically Added Room Cards

<div id="roomList">
    <button class="roomBtn">Select Deluxe Room</button>
</div>

<button id="addRoom">Add Another Room</button>

<script>
$(function () {
    $("#roomList").on("click", ".roomBtn", function () {
        $(this).text("Room Selected");
    });

    $("#addRoom").on("click", function () {
        $("#roomList").append(
            '<button type="button" class="roomBtn">Select New Room</button>'
        );
    });
});
</script>

How It Works

The parent element #roomList listens for click events from descendants matching .roomBtn. Buttons added later can therefore use the same handler without attaching a new handler to each one.

Practical application: Dynamic product lists, search results, dashboard tables, and booking interfaces.

13. Complete Practical Project: Interactive Booking Form

The following project combines click, change, input, and submit events in a simple hotel booking form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Interactive Hotel Booking Form</title>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 500px;
            margin: 40px auto;
            padding: 20px;
            background: #f5f6fa;
        }

        form {
            background: white;
            padding: 20px;
            border-radius: 10px;
        }

        label {
            display: block;
            margin-top: 14px;
        }

        input, select, button {
            box-sizing: border-box;
            width: 100%;
            padding: 10px;
            margin-top: 6px;
        }

        button {
            border: 0;
            background: #164e63;
            color: white;
            cursor: pointer;
        }

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

    <h1>Hotel Booking Request</h1>

    <form id="bookingForm">
        <label for="guestName">Guest Name</label>
        <input type="text" id="guestName" required>

        <label for="room">Room Type</label>
        <select id="room" required>
            <option value="">Choose a room</option>
            <option value="Deluxe Room">Deluxe Room</option>
            <option value="Family Room">Family Room</option>
            <option value="Suite Room">Suite Room</option>
        </select>

        <p id="roomInfo">Please select a room type.</p>

        <button type="submit">Submit Request</button>

        <p id="message" aria-live="polite"></p>
    </form>

    <script>
        $(function () {
            $("#room").on("change", function () {
                const roomName = $(this).val();

                $("#roomInfo").text(
                    roomName ? "Selected: " + roomName :
                    "Please select a room type."
                );
            });

            $("#bookingForm").on("submit", function (event) {
                event.preventDefault();

                const guestName = $("#guestName").val().trim();
                const roomName = $("#room").val();

                if (!guestName || !roomName) {
                    $("#message").text(
                        "Please complete all required fields."
                    );
                    return;
                }

                $("#message").text(
                    "Request prepared for " + guestName +
                    " - " + roomName + "."
                );
            });
        });
    </script>

</body>
</html>

Project Explanation

  1. The change event updates the selected room information.

  2. The submit event handles the form submission.

  3. preventDefault() stops the normal page reload.

  4. .val() reads the entered values.

  5. .text() displays the result safely as text.

This is a front-end demonstration only. It does not save a reservation, check room availability, or send data to a server. A production booking system needs a backend endpoint and server-side validation.

14. Common jQuery Event Mistakes

Forgetting to Load jQuery

Load the jQuery library before executing code that uses $.

Using the Wrong Selector

Check that the selector matches the ID, class, or element in your HTML.

Forgetting preventDefault()

When you need to handle a form submission without the browser's normal navigation, call event.preventDefault() in the submit handler.

Relying Only on Client-Side Validation

Browser-side validation improves usability but can be bypassed. Validate all important data on the server.

Using Hover for Essential Actions

Hover interactions are not reliable on every touch device. Make important features accessible through clicks, keyboard interaction, and clear controls.

15. Frequently Asked Questions

What are jQuery events?

jQuery events let developers respond to user interactions, such as clicks, typing, selections, and form submissions.

What is the difference between click() and on("click")?

Both can register click handlers. The on() method is more flexible and supports event delegation for dynamically added elements.

What is the difference between input and change?

The input event responds as a field's value changes. The change event fires when a change is committed, which for text fields commonly happens when the field loses focus.

What is event delegation?

Event delegation allows a parent element to handle events from matching child elements, including children added dynamically later.

Can jQuery events be used in PHP and CodeIgniter 4?

Yes. jQuery can handle interactions in CodeIgniter views and send requests to PHP controller endpoints. The server must still validate requests and enforce authorization.

Conclusion

jQuery events help make websites interactive by responding to clicks, mouse movement, keyboard input, field changes, and form submissions. Understanding these events is an important step toward building useful front-end features.

Practise the examples in your browser and then try combining multiple events in a single project.