I have a function that is important to a complex navigation UI, so I want it to be keyboard accessible. I’m writing my handler using both click and focus:
$('.mycoolnavbutton').on("click focus", function() {
// do an animated reveal
});
Here’s the gotcha: as written, I’m getting double execution (and wonky behavior) in Firefox, because the click event triggers the focus event. Everything executes (and console.logs) twice. (Webkit only executes once.)
It’s occurred to me that I could just “pipe” the click handler over to the focus:
$('.mycoolnavbutton').on("click", function(event) {
event.preventDefault();
this.focus();
});
$('.mycoolnavbutton').on("focus", function() {
// do an animated reveal
});
But that seems really weird and error-prone. I’m sure I’m not the first to encounter this dilemma. What’s the standard solution?
First, I’d ask why you’re firing a button when it gets keyboard focus? Buttons are normally triggered with the keyboard by pressing the spacebar or return key AFTER the acquire focus, and are not fired when just acquiring focus.
Then, as these two events are completely separate and there is no way to know if one will lead to theother, I can think of these possibilities for how to make sure you only fire your event once:
When you process one of these events, set some state that records the time you processed the event and then ignore any other triggers within xx milliseconds of that time.
Or, a slightly different way of accomplishing the same thing. When you firing the event, do a setTimeout and don’t process the event again until the timer fires, keeping you from ever firing twice in a short period of time.