jQuerybeast
jQuerybeast

Reputation: 14490

How to: If fadeIn do not fade again (jQuery)

I have this simple code that when you press a key it fades in a div. When I press it twice, it fades it twice. Is it possible you can prevent this with a simple line or two? Like if fadein do not fadeIn again or something?

The code looks like:

jQuery(document).bind('keydown', 's',function (evt){
   $("#div1").fadeIn();
   return false;
});

Thanks alot.

Upvotes: 2

Views: 638

Answers (3)

meouw
meouw

Reputation: 42140

Instead of using $.bind() use $.one(). This will bind your handler to the event and automatically unbind it after the first run.
http://api.jquery.com/one/

jQuery(document).one('keydown', 's',function (evt){
   $("#div1").fadeIn();
   return false;
});

Upvotes: 0

Hussein
Hussein

Reputation: 42808

No sure what you mean. Your code works. Assuming div is hidden by default, when key is pressed, div fades is. If key is pressed again, it will not fadein again since it's already showing, unless of course you are refreshing the page.

Check http://jsfiddle.net/F8s8X/.

Upvotes: 1

ysrb
ysrb

Reputation: 6740

Try this:

var isFading = false
jQuery(document).bind('keydown', 's',function (evt){
   if(!isFading){
     isFading = true;
     $("#div1").fadeIn(400,function(){ isFading = false; });
     return false;
   }
});

Upvotes: 0

Related Questions