views:

23

answers:

1

Hi,

I am curious how does the Opera browser implement it's keyboard navigation, where you can do Shift+(Up|Down|Left|Right) and you travel along a row or a column. How would you implement this in javascript?

Thanks

A: 

Here's a starting-point:

function getCentrePosition(el) {
    var x= el.offsetWidth/2, y= el.offsetHeight/2;
    while (el!==null && el.nodeType==1) {
        x+= el.offsetLeft;
        y+= el.offsetTop;
        el= el.offsetParent;
    }
    return [x, y];
}

function arrowKeyHandler(event) {
    if (event===undefined) event= window.event;
    if (!event.shiftKey) return true;

    // Detect which arrow key is pressed. Make a matrix to rotate each
    // case onto the default case for left-pressed.
    //
    var m;
    if (event.keyCode===37) m= [[1,0], [0,1]]; // left
    else if (event.keyCode===38) m= [[0,1], [-1,0]]; // up
    else if (event.keyCode===39) m= [[-1,0], [0,-1]]; // right
    else if (event.keyCode===40) m= [[0,-1], [1,0]]; // down
    else return true;

    // Find link with shortest distance in left and vertical directions.
    // Disregard any links not left of the current link.
    //
    var pos= getCentrePosition(this);
    var bestlink= null, bestdist= null;
    for (var i= document.links.length; i-->0;) {
        var otherpos= getCentrePosition(document.links[i]);
        var dx= (otherpos[0]-pos[0])*m[0][0] + (otherpos[1]-pos[1])*m[0][1];
        var dy= (otherpos[0]-pos[0])*m[1][0] + (otherpos[1]-pos[1])*m[1][1];
        if (dx>=0) continue;
        var dist= Math.abs(dx)+Math.abs(dy)*3; // arbitrary biasing factor
        if (bestdist===null || dist<bestdist) {
            bestlink= document.links[i];
            bestdist= dist;
        }
    }

    // Focus closest link in that direction, if any
    //
    if (bestlink!==null)
        bestlink.focus();
    return false;
}

// Add to each link on-page, except on Opera which already does it
//
if (!window.opera)
    for (var i= document.links.length; i-->0;)
        document.links[i].onkeydown= arrowKeyHandler;

This is a simple hack that guesses the ‘best’ link in one direction by looking at the centre point of the each link compared with the current one (normalised for direction with a rotation matrix). You could probably improve this by looking at the right-edges of links when moving left, the left-edges when moving right, and so on. And probably it should be compiling a list of all focusable elements on the pages (including form fields and elements with tabindex) instead of just links.

bobince