I have jQuery code which makes an array of focusable elements and binds .keydown for the left and right arrows to tab through them. In Chrome, IE, and Safari beginning with preventDefault()
or ending with a return false (which technically I don't want to use because I have no need to stopPropagation()
) prevents the default event of the arrows, but in Firefox it does not.
How can I prevent the default action in Firefox as well?
Here is the code, which works as expected, except in Firefox where the default event fires in addition to my callback.
$(function () {
var focusables = $(":focusable");
focusables.eq(0).focus();
focusables.eq(0).select();
focusables.each(function () {
$(this).keydown(function (e) {
if (e.which == '37') { // left-arrow
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current - 1).length ? focusables.eq(current - 1) : focusables.eq(0);
next.focus();
next.select();
}
if (e.which == '39') { // right-arrow
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
next.select();
}
});
});
});