How to attach an event handler only once?
To run an event handler only once in jQuery, you can use the .one() method. This method attaches an event handler to an element that will be executed once and then automatically unbinds itself. Here's a detailed explanation with examples:Syntax:
- selector: The element(s) to which you want to attach the event handler.
- event: The type of event (e.g., "click", "mouseenter", "keydown").
- handler: The function to execute when the event occurs.
jQuery one() method
The jQuery one() method adds event handlers to the selected element. The handler is executed at most once per element per event type.
Running a Document Ready Event Handler Only Once
You can also use .one() with the document ready event to execute code only once when the page is fully loaded:
In this case, the code inside the event handler will execute once when the DOM is ready, but subsequent ready events won't trigger it again.
By using the .one() method, you can ensure that an event handler runs only a single time, which is useful for scenarios where you want to perform an action just once when an event occurs or when the document is ready, without the need to manually unbind the event handler.