I have jQuery code that creates an array of focusable elements and binds .keydown for left and right arrows to iterate over them. In Chrome, IE, and Safari, starting with preventDefault()or ending with returning false (which I technically don’t want to use because I don’t need to stopPropagation()), prevents the default event for arrows, but in Firefox it doesn’t.
How can I prevent the default action in Firefox?
Here is code that works as expected, with the exception of 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();
}
});
});
});
source
share