Tuesday, March 11, 2014

Scroll to selection using rangy

Rangy, like ierange before it, is great for reliably selecting text programmatically across browsers. It uses the W3C Range model and applies it to all modern browsers, greatly simplifying a task that is not covered in jQuery. But, what rangy does not do is provide a way to scroll to a selection. In cases where the selected text is off-screen, it is necessary to scroll the document down so the user can see it. A selection does not have a bounding box in rangy, so there is no way to tell where it is. The only way to get that information is to enclose it in a node, and then position that node in the centre of the screen. Provided that the node-wrapping is possible this method will suffice:

function scrollToSelection( sel )
{
    var node = document.createElement("span");
    sel.surroundContents(node);
    var scrollDist = node.offsetTop 
        - (window.innerHeight+node.offsetHeight)/2;
    if ( scrollDist > 0 )
        window.scrollBy(0,scrollDist);
}

If the selection covers parts of various elements you could wrap each separate text-node in a <span>, then compute the bounding box of the entire thing. But for my purposes the above suffices.

1 comment:

  1. thanks it is completely workable on various versions of android webkit

    ReplyDelete