I have a series of buttons and other controls. When the user presses the Shift and *, I want to move to the next control (a button, text or any other control). How can i do this in the shortest possible way.
$("#theNextButton").focus();
and as far as doing shift + another key that is done like so:
var isShiftDown = false;
$(document).keyup(function (e) {
if(e.which == 16){
isShiftDown = false;
}
}).keydown(function(event){
var code = event.keyCode;
if(code == 16){ //left
isShiftDown = true;
}
if(code == 37 && isShiftDown){ //left
//instead of traping left key, trap what you need
}
});
you will have to come up with a way to focus on the "next" control yourself. it shouldnt be too hard. im going to play some fallout now.
This is admittedly a cheesy solution but here goes.
Some explanation as to what this is trying to do. I'd love corrections here, so please fire away.
Get all elements of class "nav." These are the elements to which we want to switch focus.
From this set, find the previously focused element and its index. Unfortunately, Internet Explorer and FireFox either don't provide a way or differ in their means of determining which element has focused. I'm cheating here with a custom "isFocused" attribute.
If there was no previously focused element, set the very first element in the set to focused and add the isFocused attribute to it.
If there was a previously focused element, remove the isFocused attribute from it and find the next "nav" element after it. This code supports starting over from the beginning of the set, so if you focus the last element with this technique and press Shift + "*", the first element will be focused.
There are problems with this approach. It's narrow minded, and it disregards elements focused manually by the user. It also assigns a click handler to the HTML element to catch all activity. This may not be the most performant way of handling this need.
$(document).ready
(
function()
{
$("html").keydown
(
function(e)
{
if(e.shiftKey && e.keyCode == 42)
{
var wrappedElemSet = $(".nav");
var focusedElementIndex = -1;
var focusedElement;
var elems = wrappedElemSet
.each
(
function(i)
{
if($(this).attr("isFocused"))
{
focusedElementIndex = i;
focusedElement = $(this);
return false;
}
}
)
if(focusedElementIndex == -1)
{
$(wrappedElemSet[0])
.attr("isFocused", "isFocused")
.focus();
}
else
{
var elementIndexToFocus =
focusedElementIndex == wrappedElemSet.size() + 1 ?
0 : focusedElementIndex + 1;
focusedElement.removeAttr("isFocused");
$(wrappedElemSet[elementIndexToFocus])
.attr("isFocused", "isFocused")
.focus();
}
}
}
);
}
);