Werner
Werner

Reputation: 2154

html element got focused by mouse or keyboard

How can I find out a HTML-Element (lets say a select-tag) got focus by mouse-click, keyboard or JavaScript function?

<select onfocus="foo(event)"></select>

<script>
function foo(e) {
    if (e.??? == 'mouse') {
        //do something
    }
    else if (e.??? == 'keyboard') {
        //do something different
    }
}
</script>

I also tried to add an onclick event to the element but the onfocus event fires first.

Upvotes: 0

Views: 2791

Answers (3)

user3222498
user3222498

Reputation:

If you want to check wheather < select > is clicked by keyboard or mouse, you can use mousedown() and keypress() event

$('select').mousedown(function(e){
  //your code on mouse select
});

and

$('select').keypress(function(e){
  //your code on key select
});

Upvotes: 0

Blake Simpson
Blake Simpson

Reputation: 1088

I don't believe there is any native way to see how the element received its focus (correct my if I'm wrong!).

However, you may be able to do something like store when the mouse is clicked, store when the keyboard is used and then react based on the last active state.

var inputState = null;

document.addEventListener("click", handleClick);
document.addEventListener("keyup", handleKey);

function handleClick () {
    inputState = "mouse";
}

function handleKey () {
    inputState = "keyboard";
}

function foo() {
    if ( inputState === "mouse" ) {
         // mouse code   
    } else if ( inputState === "keyboard" ) {
         // keyboard code   
    } else {
         // Function was called directly   
    }

    // Reset input State after processing
    inputState = null
}

This will likely need some adjustments but I hope you can use this to find the correct answer.

Edit:

My answer is a vanilla JS solution, if you have access to jQuery you may want to investigate the click and keyup event handlers.

Upvotes: 2

A Paul
A Paul

Reputation: 8251

Use document.activeElement, it is supported in all major browsers. It can give you the current active element.

EDIT

Oops I think I misunderstood your question. you want to identify the mouse or keyboard or programmatic

For programmatic if(e.hasOwnProperty('originalEvent')) { // Focus event was manually triggered. }

To differentiate between keyboard and mouse based focus events You have to hack it by adding an extra keydown event and understand. You can not differentiate it like you want.

Upvotes: 0

Related Questions