What Does the jQuery one() Method Do?

The jQuery one() method is an event-handling function designed to execute an event handler exactly once per element. This article explains how the one() method works, outlines its syntax and parameters, compares it to the standard on() method, and highlights practical use cases where single-execution event listeners are needed in web development.

Understanding the jQuery one() Method

The one() method attaches a handler to an event for the selected elements, identical to the standard on() method, with one crucial difference: the handler is unbound immediately after it executes for the first time. Any subsequent triggers of the same event on that element will not run the function again.

Syntax

The basic syntax for the one() method is as follows:

$(selector).one(event, data, handler);
  • event (String, Required): One or more JavaScript event types, such as click, submit, mouseenter, or custom events.
  • data (Object, Optional): Data passed to the event handler object (event.data) when the event is triggered.
  • handler (Function, Required): The function to execute when the event occurs.

Event Delegation Syntax

Like on(), the one() method also supports delegated events for dynamically added elements:

$(parentSelector).one(event, childSelector, data, handler);

Basic Code Example

Here is a common scenario using the one() method to track an initial user interaction:

$("#submit-button").one("click", function() {
    console.log("This will only log once.");
    $(this).prop("disabled", true);
});

In this example, the click event runs once. If the element is clicked a second time, the event handler is no longer attached, preventing any repeated execution.

jQuery one() vs. jQuery on()

  • $(selector).on(): Attaches a persistent listener that fires every time the specified event occurs until it is explicitly detached using $(selector).off().
  • $(selector).one(): Automatically detaches itself after its first execution. It eliminates the manual cleanup required when manually calling off() inside an on() callback.

Handling Multiple Events

You can supply multiple space-separated events to the one() method. When doing so, the handler runs once for each event type:

$("img").one("mouseenter mouseleave", function(event) {
    console.log("Triggered event: " + event.type);
});

In this case, the function triggers once on the initial mouseenter and once on the initial mouseleave.

Common Practical Use Cases

  • Preventing Duplicate Submissions: Ensuring a user cannot click a form submission or checkout button multiple times while the request processes.
  • Lazy Loading Resources: Fetching external data, initializing heavy plugins (such as map widgets or carousels), or rendering complex UI components only when a user interacts with a container for the first time.
  • Onboarding Tooltips: Displaying an introductory tutorial tip or guidance pop-up the first time a user focuses on an input field.