Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine focus event: click or tabstop

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();
    }
});
like image 434
rob waminal Avatar asked May 27 '11 05:05

rob waminal


People also ask

Does click trigger focus?

Triggering a click synthetically does not cause focus to switch to the element, however the click triggered by hardware does.

How do you know if an event is clicking?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

What triggers focus event?

The focus event fires when an element has received focus. The event does not bubble, but the related focusin event that follows does bubble. The opposite of focus is the blur event, which fires when the element has lost focus. The focus event is not cancelable.

What is the difference between focus and Focusin events in jquery?

The focusin event fires when an element has received focus, after the focus event. The two events differ in that focusin bubbles, while focus does not. The opposite of focusin is the focusout event, which fires when the element has lost focus. The focusin event is not cancelable.


1 Answers

If 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.net/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 come back.
    $this.removeData('mdown');

    // Check if the mousedown event fired before the focus
    if(mdown){
        // Click
    } else {
        // Tab
    }
});
like image 157
DarthJDG Avatar answered Oct 06 '22 01:10

DarthJDG