How to determine the focus event on jQuery if the focus is fired on click event or tabstop? I have this focus event that if the focus is fired by a tabstop I will execute something and if it is a click I will not execute it.
Here's a pseudo code
$('a').focus(function(){
if(ThisIsTabStop()) {
IWillExecuteThis();
}
});
How to determine the focus event on jQuery if the focus is fired on click event or tabstop? I have this focus event that if the focus is fired by a tabstop I will execute something and if it is a click I will not execute it.
Here's a pseudo code
$('a').focus(function(){
if(ThisIsTabStop()) {
IWillExecuteThis();
}
});
Share
Improve this question
asked May 27, 2011 at 5:53
rob waminalrob waminal
18.4k18 gold badges52 silver badges65 bronze badges
2
-
2
I don't have a concrete answer, but one way might be to use the
keypress()
event to store the time the Tab key was last pressed, and if it was a very short time ago, you can be fairly confident it is a tab stop. Also, to detect a click, bind to the click event. I'm not sure which executes first, but maybe setting a data item on the element in the click handler and checking for that data item in the focus handler would be another way to go. – GregL Commented May 27, 2011 at 5:57 -
The
focus
event always fires before theclick
, butmousedown
fires beforefocus
. – DarthJDG Commented May 27, 2011 at 8:52
1 Answer
Reset to default 10If an element is clicked, the mousedown
event fires before focus. You just need to set a data attribute, and check it in the focus event.
Try this demo: http://jsfiddle/KcGcF/1/
$('a').mousedown(function(e){
var $this = $(this);
// Only set the data attribute if it's not already focused, as the
// focus event wouldn't fire afterwards, leaving the flag set.
if(!$this.is(':focus')){
$this.data('mdown',true);
}
});
$('a').focus(function(e){
var $this = $(this);
var mdown = $this.data('mdown');
// Remove the flag so we don't have it set next time if the user
// uses the tab key to e back.
$this.removeData('mdown');
// Check if the mousedown event fired before the focus
if(mdown){
// Click
} else {
// Tab
}
});