Reputation: 38705
Here is my base case. If I click on Text
, a text box will fade in, and put a focus on that text box. When I press Esc, the text box will disappear and the Text
will fade back in. http://jsfiddle.net/FDjUm/. I have two questions. Please refer to the below jsfiddle for visual demonstration of my questions
1) http://jsfiddle.net/FDjUm/4/
I put in an alert box in the focus
, and it get called infinitely. Why is that and how can I fix it?
2) http://jsfiddle.net/Zh8HR/13/
I put in an alert box in the fadeIn
. The alert get called multiples times (not infinitely). So I put return false
then the first time (the first click and press Esc), it work great (alert box only appear 1 time). But the more you click and esc, the more time the alert box appear? Why and how to fix it?
I am new to jQuery, so be criticized if the way I write jQuery is improper. And i want to learn and write good code.
Upvotes: 0
Views: 367
Reputation: 72681
The alert causes the focus to lose. After clicking ok the focus returns.
Which causes the alert to be displayed which causes the focus to lose. etc etc etc
For number 2
Just move the keyup
outside th focus function.
Lemme fix that fiddle for you. 1 sec...
here you go :)
EDIT
Bit better code:
Upvotes: 1
Reputation: 11096
the fix for the first one (and maybe the second) is to change the line
jQuery("#textBox").focus();
to use the $.triggerHandler() function :
jQuery("#textBox").triggerHandler('focus');
Upvotes: 1
Reputation: 7427
Maybe you could remove the focus on ESC key:
jQuery("#textBox").blur().hide();
I think that you hide the textbox, but the textbox still have the focus...
Upvotes: 1