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).one(event, handler);
  1. selector: The element(s) to which you want to attach the event handler.
  2. event: The type of event (e.g., "click", "mouseenter", "keydown").
  3. 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.

$("button").one("click", function(){ alert("Only once"); });
<button>Message show only once</button>
run this source code Browser View
Full Source
<html> <head> <title>jQuery events executed only once</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").one("click", function(){ alert("Only once"); }); }); </script> </head> <body> <button>Message show only once</button> </body> </html>

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:

$(document).one("ready", function() { console.log("Document is ready. This will only happen once."); });

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.

Conclusion

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.