I am Using rangy to select a text in an IFrame selection is working but some times i need to scroll IFrame to view this selection. it is possible automatically scroll IFrame to the selected text?
You could use the scrollIntoView()
method of the element containing the selection's anchor node, but that may scroll the main document as well as the iframe, and may also be inexact if the selection starts several lines into a text node, for example.
var sel = rangy.getSelection();
var anchorNode = sel.anchorNode;
if (anchorNode) {
if (anchorNode.nodeType != 1) {
anchorNode = anchorNode.parentNode;
}
anchorNode.scrollIntoView();
}
A better bet may be to use the selection range's bounding rectangle, available via the range's getBoundingClientRect()
method in most modern browsers, and scroll the iframe's document manually. However, this is not universally supported and is relative to the viewport rather than the document. Here's a related question and answer: