简体   繁体   中英

How to execute a code on focus of textarea just once?

I have a teatarea like this:

 $("textarea").on('focus', function(){ alert("clicked"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea col="3" row="20"></textarea> 

As you see in the above fiddle, every time when you focus on that textarea, alert() executes. How can I limit it to executes just one time? (just first time)

You can use jQuery's one()

$("textarea").one('focus', function(){
  alert("clicked");
});

The handler is executed at most once per element per event type.

You can use a counter system that way if your change your mind on how many times you want to trigger the alert on focus you can just change the if then statement value.

//initalize the counter
var count = 0;

//set the limit
var limit = 0;

//on focus event
$("textarea").on('focus', function(){

   //if the count equals the limit
   if(count === limit){

     //alert the message
     alert("clicked");

   }

//increment the count
count++;

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM