Fire event only once using Jquery .one() function

Fire event only once using Jquery .one() function

By Yashwant Chavan, Views 1234, Date 08-Sep-2015

Sometimes we need to fire event on element only once. Jquery .one() function prevent events from firing multiple times.

tags jquery jquery-events

Jquery .one() Syntax

.one();
.one( events [,data ],handler );
.one( events [,selector][,data ],handler );
.one( events [,selector ][,data ]);

In below examples. We are using .one() event binding method whose handler is executed at once per element per event type.

Bind .one() method on div element

$( "div" ).one( "click", function() {
  console.log( "Executed only once." );
});

Bind .one() method on id selector

$( "#element" ).one( "click", function() {
  console.log( "Executed only once." );
});

Bind .one() method on class selector. Here we have attached multiple events "click" and "mouseenter". In multiple events it while display console message one for "click" and one for "mouseenter".

$( ".class" ).one( "click mouseenter", function() {
  console.log( "Executed only once." );
});

Jquery .one() Example

<!DOCTYPE html>
<html>
   <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
      <script>
         $(document).ready(function(){      
          $(".box").one("click mouseenter", function(){ 
         console.log($(this).attr("class"));
         var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);   
         $(this).css("background-color",randomColor);
          });
         });  
      </script>   
   </head>
   <style>
      .box{  
      height:100px;
      width:100px;  
      padding:10px;
      margin:10px;
      float:left;
      display:inline-block;
      background:#ff9900;  
      }
   </style>
   <body>
      <h1>Jquery .one() function Example</h1>
      <div id="container">
         <div class="box"></div>
      </div>
   </body>
</html>

Output

jquery .one() function example

Finish

Hope this Tutorial is useful to you, Please fill free to provide your comments if there is any problem. Thanks

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]