Paramclasses Academy - Blog

Tutorials Details

←
Post 3 of 15
→

What Are jQuery Events?

What Are jQuery Events?

October 14, 2026

What Are jQuery Events? Types, Methods and Examples

Introduction to jQuery Events

Websites become interactive when they respond to user actions. For example, when a user clicks a button, enters text into a search box, moves the mouse over an image or submits a form, an event occurs.

jQuery events help developers detect these actions and execute specific code in response.

For example, you can use a click event to display a message, a mouse event to change a card's background color, or a form event to validate user input.

In this tutorial, you will learn what jQuery events are, their different types, how event methods work and how to use them in practical examples.

What Are jQuery Events?

jQuery events are actions or occurrences detected by the browser that allow a webpage to respond to user interactions.

Some common examples are:

  • Clicking a button.

  • Double-clicking text.

  • Moving the mouse over an element.

  • Typing into an input field.

  • Focusing on a form field.

  • Submitting a registration form.

  • Scrolling a webpage.

jQuery provides methods such as on() to attach event handlers to HTML elements.

Basic Syntax of jQuery Events

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

Explanation:

  • $() selects the required HTML element.

  • selector identifies the element, such as a button or input field.

  • on() attaches an event handler.

  • eventName specifies the event, such as click, keyup or submit.

  • function() contains the code that runs when the event occurs.

1. jQuery Click Event

The click() event occurs when a user clicks an HTML element. It is commonly used with buttons, links, icons and other interactive elements.

The modern recommended approach is to attach click handlers using on("click", ...).

Example: Click Event

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

    <button id="myButton">Click Me</button>
    <p id="message">Waiting for your action...</p>

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

    <script>
        $(document).ready(function () {
            $("#myButton").on("click", function () {
                $("#message").text("Button clicked successfully!");
            });
        });
    </script>

</body>
</html>

Output

Initially, the paragraph displays:

Waiting for your action...

After clicking the button, it displays:

Button clicked successfully!

Explanation

  1. $("#myButton") selects the button using its ID.

  2. .on("click", function () {}) attaches a click event handler.

  3. The function runs when the button is clicked.

  4. $("#message") selects the paragraph.

  5. .text() changes the paragraph's text.

Where Is the Click Event Used?

  • Login and registration buttons.

  • Add to Cart buttons.

  • Delete buttons.

  • Show and Hide buttons.

  • Interactive menus.

2. jQuery Double-Click Event

The dblclick event occurs when a user double-clicks an element.

It can be useful for interactive interfaces where an action should occur after a double-click.

Example: Double-Click Event

<p id="myText">Double-click this text.</p>

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

<script>
    $(document).ready(function () {
        $("#myText").on("dblclick", function () {
            $(this).css("color", "red");
        });
    });
</script>

Output

When the user double-clicks the paragraph, its text color changes to red.

Explanation

  • dblclick detects a double-click.

  • $(this) refers to the element that triggered the event.

  • .css("color", "red") changes its text color.

3. jQuery Mouse Events

Mouse events allow a webpage to respond to mouse actions.

Common mouse events include:

Event Description
click Occurs when an element is clicked.
dblclick Occurs when an element is double-clicked.
mouseenter Occurs when the mouse pointer enters an element.
mouseleave Occurs when the mouse pointer leaves an element.
mousedown Occurs when a mouse button is pressed down.
mouseup Occurs when a mouse button is released.
mousemove Occurs when the pointer moves within an element.

Example: Mouse Enter and Mouse Leave

<div id="box" style="padding: 30px; background: lightgray;">
    Move your mouse over this box
</div>

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

<script>
    $(document).ready(function () {
        $("#box").on("mouseenter", function () {
            $(this).css("background-color", "lightblue");
        });

        $("#box").on("mouseleave", function () {
            $(this).css("background-color", "lightgray");
        });
    });
</script>

Output

  • When the mouse enters the box, the background becomes light blue.

  • When the mouse leaves the box, the background returns to light gray.

Explanation

The mouseenter handler runs when the pointer enters the box. The mouseleave handler runs when it leaves.

This approach is useful for hover effects, navigation menus and interactive cards.

4. jQuery Keyboard Events

Keyboard events detect keyboard actions performed by a user.

They are useful for search fields, live text previews, keyboard shortcuts and interactive forms.

Common keyboard events include:

Event Description
keydown Occurs when a key is pressed down.
keyup Occurs when a pressed key is released.

The older keypress event is deprecated. For most modern applications, use keydown or keyup.

Example: Detect Typed Text

<input type="text" id="username" placeholder="Enter your name">

<p id="result"></p>

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

<script>
    $(document).ready(function () {
        $("#username").on("keyup", function () {
            let name = $(this).val();

            $("#result").text("You typed: " + name);
        });
    });
</script>

Output

If the user types Rahul, the paragraph displays:

You typed: Rahul

Explanation

  • keyup runs when the user releases a key.

  • val() retrieves the input's current value.

  • $(this) refers to the input that triggered the event.

  • text() displays the entered text.

Practical use: This technique can help display live search text or a preview of a username.

5. jQuery Form Events

Form events are used to handle user interactions with form elements.

They are particularly useful for registration forms, login pages, contact forms and search forms.

Common form events include:

Event Description
submit Occurs when a form is submitted.
change Occurs when a control's value changes and the change is committed.
focus Occurs when an element receives focus.
blur Occurs when an element loses focus.
input Occurs when an input's value changes through user interaction.

Example: Form Submit Event

<form id="registrationForm">
    <input type="text" id="fullName" placeholder="Enter your name">

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

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

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

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

            let name = $("#fullName").val().trim();

            if (name === "") {
                $("#message").text("Please enter your name.");
            } else {
                $("#message").text("Welcome, " + name + "!");
            }
        });
    });
</script>

Output

If the user submits the form without entering a name, the message is:

Please enter your name.

If the user enters Rahul, the message is:

Welcome, Rahul!

What Is preventDefault()?

preventDefault() prevents the browser's default action for an event.

In this example, it stops the form from submitting normally, allowing jQuery to display a message on the current page.

Important: Client-side validation improves the user experience, but important information must also be validated on the server.

6. jQuery Focus and Blur Events

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

These events are commonly used to highlight form fields or display helpful input instructions.

Example: Focus and Blur

<input type="email" id="email" placeholder="Enter your email">

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

<script>
    $(document).ready(function () {
        $("#email").on("focus", function () {
            $(this).css("border", "2px solid blue");
        });

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

Output

  • When the input receives focus, its border becomes blue.

  • When the input loses focus, its border becomes gray.

Explanation

The focus handler highlights the active input. The blur handler restores its normal border.

7. jQuery Change Event

The change event is useful when you want to respond to a changed input value, such as a selected country or payment option.

Example: Select Box

<select id="course">
    <option value="">Select a course</option>
    <option value="PHP">PHP</option>
    <option value="jQuery">jQuery</option>
    <option value="JavaScript">JavaScript</option>
</select>

<p id="courseMessage"></p>

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

<script>
    $(document).ready(function () {
        $("#course").on("change", function () {
            let selectedCourse = $(this).val();

            $("#courseMessage").text(
                "You selected: " + selectedCourse
            );
        });
    });
</script>

Output

When the user selects jQuery, the paragraph displays:

You selected: jQuery

Explanation

  • change detects a committed change in the select box.

  • val() gets the selected option's value.

  • text() displays the selected course.

8. jQuery on() Method

The on() method attaches one or more event handlers to selected elements.

It is a flexible and recommended approach for event handling in modern jQuery code.

Syntax

$(selector).on("eventName", function () {
    // Event handling code
});

Example

<button id="btn">Click Me</button>

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

Output: Clicking the button displays an alert containing Welcome to jQuery!.

Handling Multiple Events

You can use the same handler for more than one event.

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

This example toggles the highlight class when either event occurs. If you want separate behavior for entering and leaving, use separate handlers instead.

Event Delegation with on()

Event delegation allows you to handle events on child elements that may be added to the page dynamically.

<ul id="taskList">
    <li>Task One</li>
    <li>Task Two</li>
</ul>

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

When any list item inside #taskList is clicked, its text becomes blue. This delegated handler can also work for matching list items added later.

9. jQuery off() Method

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

Syntax

$(selector).off("eventName");

Example

<button id="myButton">Click Me</button>
<button id="removeEvent">Remove Click Event</button>

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

    $("#removeEvent").on("click", function () {
        $("#myButton").off("click");
    });
</script>

Output

  • Clicking Click Me displays an alert.

  • Clicking Remove Click Event removes the button's click handler.

  • Clicking Click Me afterward no longer triggers that alert.

In larger applications, use event namespaces or specific handler references when you need to remove only a particular handler.

10. jQuery trigger() Method

The trigger() method manually triggers an event on selected elements.

Syntax

$(selector).trigger("eventName");

Example

<button id="myButton">Click Me</button>
<button id="triggerButton">Trigger Click</button>

<script>
    $("#myButton").on("click", function () {
        alert("Click event executed!");
    });

    $("#triggerButton").on("click", function () {
        $("#myButton").trigger("click");
    });
</script>

Output

When the user clicks Trigger Click, jQuery triggers the click handler attached to Click Me, and the alert appears.

Note: Triggering an event programmatically is not the same as performing a real physical click. Browser actions that require user interaction may not be activated by a triggered event.

11. jQuery one() Method

The one() method attaches an event handler that runs only once for each matching element.

Example

<button id="welcomeButton">Click Me</button>

<script>
    $("#welcomeButton").one("click", function () {
        alert("This message appears only once.");
    });
</script>

Output

The alert appears the first time the button is clicked. Subsequent clicks do not execute this handler again.

This method is useful for one-time actions, such as showing a welcome message or initializing a simple interaction.

12. Difference Between click(), on() and trigger()

Method Purpose
click() A shorthand event method; it can attach a click handler or trigger a click event when used without a handler.
on() Attaches event handlers and supports event delegation.
trigger() Programmatically triggers an event.
off() Removes previously attached event handlers.
one() Attaches a handler that runs only once per matching element.

For new code, on() is generally a good choice for attaching event handlers because it supports direct and delegated event handling.

13. Complete Practical Example: Multiple jQuery Events

The following example combines click, mouse, keyboard and form events in one small application.

Complete HTML, CSS and jQuery Code

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

    <title>jQuery Events Example</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        .box {
            padding: 20px;
            margin: 15px 0;
            background-color: #eeeeee;
            border-radius: 8px;
        }

        button {
            padding: 10px 15px;
            margin: 5px;
            cursor: pointer;
        }

        input {
            padding: 10px;
            margin: 8px 0;
        }
    </style>
</head>
<body>

    <h1>jQuery Events Demo</h1>

    <button id="clickBtn">Click Me</button>
    <p id="clickResult"></p>

    <div class="box" id="hoverBox">
        Move your mouse over this box.
    </div>

    <input type="text" id="name" placeholder="Type your name">
    <p id="typingResult"></p>

    <form id="myForm">
        <input type="text" id="email" placeholder="Enter your email">
        <button type="submit">Submit Form</button>
    </form>

    <p id="formResult"></p>

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

    <script>
        $(document).ready(function () {

            // Click event
            $("#clickBtn").on("click", function () {
                $("#clickResult").text("Button clicked!");
            });

            // Mouse events
            $("#hoverBox").on("mouseenter", function () {
                $(this).css("background-color", "lightblue");
            });

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

            // Keyboard event
            $("#name").on("keyup", function () {
                $("#typingResult").text(
                    "Your name: " + $(this).val()
                );
            });

            // Form submit event
            $("#myForm").on("submit", function (event) {
                event.preventDefault();

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

                if (email === "") {
                    $("#formResult").text(
                        "Please enter your email."
                    );
                } else {
                    $("#formResult").text(
                        "Form submitted for: " + email
                    );
                }
            });

        });
    </script>

</body>
</html>

How to Run This Example

  1. Open Visual Studio Code.

  2. Create a file named jquery-events.html.

  3. Paste the complete code into the file.

  4. Save the file.

  5. Open it in your browser with Live Server or by opening the HTML file directly.

  6. Click the button, move your mouse over the box, type a name and submit the form.

Expected Results

  • Clicking the button displays Button clicked!.

  • Moving the pointer over the box changes its background color.

  • Typing in the name field updates the text below it.

  • Submitting an empty email field displays a validation message.

  • Submitting a non-empty email displays the entered value.

Common Mistakes in jQuery Events

1. Forgetting to Include the jQuery Library

If jQuery is not loaded, $ may be undefined and your event handler will not work.

Solution: Include the jQuery script before your own jQuery code.

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

2. Using the Wrong Selector

$("#mybutton").on("click", function () {
    alert("Clicked!");
});

If the actual element has id="myButton", the selector will not match because the ID spelling differs.

Solution: Ensure that the selector matches the HTML ID or class exactly.

3. Running Code Before Elements Are Ready

If your script runs before the target elements are available, the handler may not be attached as expected.

Solution: Use a document-ready handler or place the script after the relevant HTML elements.

$(document).ready(function () {
    $("#myButton").on("click", function () {
        alert("Clicked!");
    });
});

4. Forgetting preventDefault() for Form Submission

A form may submit normally and reload or navigate away from the current page.

Solution: If you want to handle the submission with JavaScript instead, call event.preventDefault() inside the submit handler.

5. Using keypress for New Projects

The keypress event is deprecated.

Solution: Use keydown or keyup for keyboard interactions, depending on the behavior you need.

6. Confusing text() and val()

  • text() gets or sets an element's text content.

  • val() gets or sets the value of form controls such as inputs and select boxes.

Solution: Use the method appropriate to the element you are working with.

Best Practices for jQuery Event Handling

  • Prefer .on() when attaching event handlers.

  • Use clear and meaningful IDs and class names.

  • Keep event-handler code readable and focused.

  • Use delegated events for matching elements that are added dynamically.

  • Remove handlers with .off() when they are no longer needed.

  • Prevent default behavior only when necessary.

  • Validate important form data on the server, not only in the browser.

  • Test mouse, keyboard and form interactions on mobile and desktop devices.

Frequently Asked Questions (FAQs)

1. What are jQuery events?

jQuery events allow webpages to respond to user interactions such as clicking buttons, typing text, changing form fields and submitting forms.

2. What is the click event in jQuery?

The click event runs a function when a user clicks an element.

$("#btn").on("click", function () {
    alert("Hello!");
});

3. What is the on() method in jQuery?

The on() method attaches event handlers to selected elements. It also supports event delegation for matching child elements.

4. What is the difference between keydown and keyup?

keydown occurs when a key is pressed down, while keyup occurs when the key is released.

5. What is the use of preventDefault()?

It prevents the browser's default action for an event, such as the normal submission of a form.

6. How can we remove an event handler in jQuery?

Use the off() method.

$("#btn").off("click");

7. What is event delegation in jQuery?

Event delegation attaches a handler to a parent element so it can handle events from matching child elements, including matching children added later.

8. What is the difference between trigger() and on()?

on() attaches an event handler, while trigger() programmatically triggers an event.

9. Can jQuery handle form validation?

Yes. jQuery can check form values and display messages. However, server-side validation is still necessary for security and data integrity.

10. Is jQuery useful for modern websites?

Yes. jQuery can still be useful in existing projects and websites that need straightforward DOM manipulation and event handling. New projects should also consider whether native JavaScript or a modern framework better suits their requirements.

jQuery Events Interview Questions

  1. What are events in jQuery?

  2. What is the difference between click() and on()?

  3. Explain the dblclick event with an example.

  4. What are mouse events in jQuery?

  5. What is the difference between keydown and keyup?

  6. What is the purpose of preventDefault()?

  7. How do you remove an event handler in jQuery?

  8. What is event delegation?

  9. What is the difference between trigger() and one()?

  10. How do you handle a form submission using jQuery?

Practice Exercises

Try these exercises to improve your understanding of jQuery events.

  1. Create a button that displays a message when clicked.

  2. Change a paragraph's text color when it is double-clicked.

  3. Change a box's background color when the mouse enters and leaves it.

  4. Create an input field that displays the typed text below it.

  5. Display a message when a user selects an option from a dropdown.

  6. Create a form that displays an error when the name field is empty.

  7. Use off() to remove a click handler from a button.

  8. Use one() to display an alert only once.

  9. Use trigger() to trigger a button's click handler from another button.

  10. Use event delegation to change the color of dynamically added list items.

Multiple-Choice Questions (MCQs)

1. Which jQuery method is commonly recommended for attaching event handlers?

A. show()

B. on()

C. hide()

D. css()

Correct Answer: B. on()

2. Which event occurs when a user double-clicks an element?

A. click

B. hover

C. dblclick

D. change

Correct Answer: C. dblclick

3. Which method prevents a form's default submission behavior?

A. stop()

B. preventDefault()

C. remove()

D. trigger()

Correct Answer: B. preventDefault()

4. Which method removes jQuery event handlers?

A. off()

B. val()

C. text()

D. append()

Correct Answer: A. off()

5. Which event occurs when a pressed keyboard key is released?

A. keydown

B. keyup

C. submit

D. focus

Correct Answer: B. keyup

Conclusion

jQuery events are an important part of creating interactive websites. They allow developers to respond to mouse actions, keyboard input, form submissions and many other user interactions.

In this tutorial, you learned about click events, mouse events, keyboard events, form events and important methods such as on(), off(), trigger() and one().

Practice these examples by creating small interactive webpages. Understanding event handling will also help you build more advanced projects such as To-Do applications, form validation systems, dynamic search boxes and interactive dashboards.

←
Post 3 of 15
→