Accessible jQuery event binding - click and press

Just a quick question, I think this is a lot:

$saveBtn.bind("click keypress", function(e)
{
    if (e.type != "keypress" || e.keyCode == 13)
    {
        // Do something...

        return false;
    }
});

Is there a faster way to bind an action listener to a button? I always want my buttons with event listeners to work both on clicks and on the enter key ... it looks like this would be a fairly common thing, but nothing was found on Google. Any thoughts?

Thank.

+3
source share
4 answers

Linking him to clickcomplete the task, you do not need to keep the press. Example

+3
source

You can create a second function that processes the additional logic and passes your function as a parameter:

function handleClickAndPress(myfunc)
{
    return function (e) {
        if (e.type != "keypress" || e.keyCode == 13) {
            myfunc(e);
        }
    };
}

$saveBtn.bind("click keypress", handleClickAndPress(function (e) {
    // do your stuff here
}));
+1
source

, ""?

0

A click event does not actually handle a keystroke in each case, it is a button that does the work of the click. When you use a div with the tabindex attribute to make it accessible to the keyboard, the click handler will not fire when you press the enter button.

HTML

<div id="click-only" tabindex="0">Submit click only</div>
<div id="click-and-press" tabindex="0">Submit click and press</div>

JQuery

$("#click-only").click(function (e) {
    addToBody(); // Only works on click
});

$("#click-and-press").bind("click keypress", handleClickAndPress(function (e) {
    addToBody(); // Works on click and keypress
}));

function addToBody() {
    $("body").append($("<p/>").text("Submitted"));
}

function handleClickAndPress(myfunc) {
    return function (e) {
        if (e.type != "keypress" || e.keyCode == 13) {
            myfunc(e);
        }
    };
}

Therefore, to answer the question, I do not think that there is a better way (which works in each case), except for the yoda2k solution.

0
source

All Articles