Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery trigger action on focus or click but not both

I have this sample code:

$myTrigger
    .click(function(e){
         alert('click');
    })
    .focus(function(e){
         alert('focus');
         $(this).click()
    })

The intent is that I want something to happen when you click on $myTrigger. If, on the other hand, you tab onto it via the keyboard (ie, focus) I want the exact same thing to happen, so I ask it to click.

The catch is if I click on it, it also focuses. So both alerts are going off.

Is there a way to prevent the focus event from going off when clicking?

UPDATE:

Ajm's comment got me thinking that I'm maybe asking the wrong thing.

Question: Does a click event always also trigger focus in javascript (and/or in jQuery?). Can I assume whenever I want to handle both clicking with the mouse and tabbing-in with the keyboard, the focus() event will handle both?

Or is it dependent on the particular element that I'm attaching the events to? (In this case $myObject happens to be an anchor tag (link).

like image 817
DA. Avatar asked Mar 16 '10 21:03

DA.


3 Answers

jQuery has a built-in functon for this that's not used all that often called .one()

$mytrigger.one('click focus', function() { alert("event"); });

This will only trigger once, or you can re-bind if you want afterwards.

like image 158
Nick Craver Avatar answered Nov 02 '22 00:11

Nick Craver


To trigger click() for TAB focus (and prevent click() from being triggered twice when focus comes from a mouse click), I did the following:

$('#item').mousedown(function(){
    $(this).data("mouseDown", true);
});

$('#item').mouseup(function(){
    $(this).removeData("mouseDown");
});

$('#item').focus(function(){
    if (!$(this).data("mouseDown"))
        $(this).click();
});

Does that work good for you?

like image 20
Walid Avatar answered Nov 02 '22 01:11

Walid


Another option is:

$myTrigger
    .mousedown(function(e) {
        e.preventDefault();  // don't grab focus
    })
    .click(function(e) {
         alert('click');
    })
    .focus(function(e) {
         alert('focus');
         $(this).click()
    });

This will leave the keyboard focus wherever it was before when clicking the button, while still allowing the button to become focused via Tab (or programmatically calling .focus() on it).

like image 2
peterflynn Avatar answered Nov 02 '22 01:11

peterflynn