How to Make an Event Call Only Once in jQuery

Introduction

Today we will learn how to fire an event only once in jQuery. This is a simple demo of the jQuery one() function. I hope you will like it.

Please see to this article in my blog.

Background

While I was doing some tasks, I wanted to make a click event that is to be fired only once for a user when the user is logged in. I used the jQuery one function to do it, so I thought of sharing it with you all.

Using the code

As you all know we can handle many events in the client side using jQuery. Here I am sharing with you one of those events that will definitely help you one day in your application.

To start with loading the jQuery reference, I will use the Google CDN here:

  1. <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>   
Now we will create a "p" tag.
  1. <p>Click Me</p>   
What next? Style that "p" tag?
  1. p {   
  2.    color: red;   
  3.    width: auto;   
  4.    height: 50px;   
  5.    margin: 250px;   
  6.    border: 1px solid #ccc;   
  7.    padding: 25px;   
  8.    text-align: center;   
  9. }   
Now it is time to start our jQuery coding. For that we will create a document ready event and a click event.
  1. <script>   
  2.    $(document).ready(function(){   
  3.       $("p").one( "click", function() {   
  4.          $(this ).text("You clicked me!. Now you can't do anything!!!!");   
  5.       });   
  6.    });   
  7. </script>   
So what this one() function does is it ensures that elements of the click event is fired only once.

Complete Code
  1. <html>  
  2.     <head>  
  3.         <title>JQuery one demo - Sibeesh Passion</title>  
  4.         <style>   
  5.             p {   
  6.               color: red;   
  7.               width: auto;   
  8.               height: 50px;   
  9.               margin: 250px;   
  10.               border: 1px solid #ccc;   
  11.               padding: 25px;   
  12.              text-align: center;   
  13.             }   
  14.       </style>  
  15.         <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>  
  16.     </head>  
  17.     <body>  
  18.         <p>Click Me</p>  
  19.         <script>   
  20. $(document).ready(function(){   
  21.     $("p").one( "click", function() {   
  22.         $(this ).text("You clicked me!. Now you can't do anything!!!!");   
  23.     });   
  24. });   
  25. </script>  
  26.     </body>  
  27. </html>   
Now we will see the output.

Output
 
 
 
 
 
Conclusion

I hope you will like this article. Please share with me your valuable thoughts and comments. Your feedback is always welcome.

Thanks in advance. Happy coding!