Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the start and end position of user selection using javascript from a parent element

I'm looking for a way to calculate the start and end position of a users selection from a known parent element. I came across this with some slight modification I was able to get working for FF, but I'm not sure how to do this in IE and I'd love to get some thoughts if my modification is appropriate. Big thanks to Tim Down for the original answer.

function getBodyTextOffset(node, offset) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(document.getElementById('test'));
    range.setEnd(node, offset);
    sel.removeAllRanges();
    sel.addRange(range);
    return sel.toString().length;
}

function getSelectionOffsets() {
    var sel, range;
    var start = 0, end = 0;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(sel.rangeCount - 1);
            start = getBodyTextOffset(range.startContainer, range.startOffset);
            end = getBodyTextOffset(range.endContainer, range.endOffset);
            sel.removeAllRanges();
            sel.addRange(range);
            alert(start + ", " + end);
        }
    } else if (document.selection) {
        // IE stuff here
    }
    return {
        start: start,
        end: end
    };
}

I know this has been a while but here is a JSFiddle showing the idea. Again it works in FF and Chrome but not IE9. Ideally I'd like to be able to get the offset from the beginning of the element test.

like image 515
Jamie Avatar asked Jan 22 '12 03:01

Jamie


People also ask

How do you find the position of an element relative to a parent?

In order to get the location of an element relative to the document, jQuery offset() method is used. The offset() method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element.

What is getSelection in JavaScript?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.

How do you create a selection in JavaScript?

select() – selects everything in the text control (can be textarea instead of input ), input. setSelectionRange(start, end, [direction]) – change the selection to span from position start till end , in the given direction (optional).

What is a range object in JavaScript?

The Range object supports properties and methods for several activities. With a Range object: you can retrieve and modify any part of the document. you can get the placement and several other geometrical properties of a contiguous part of the document. you can get and modify the selected content of the document.


1 Answers

JavaScript range is a painful topic though here are some good resources...

Here are some demos that you can use as reference...

http://dylanschiemann.com/articles/dom2Range/dom2RangeExamples.html

A vague though decent starting point to understand what methods and properties are available... http://help.dottoro.com/ljxsqnoi.php

You can discover what contains what using the following JavaScript...

for (i in window.getSelection()) {alert('i = '+i);}

When you see an object mentioned you can append it, just make sure you know to also use parenthesis for methods and on rare occasion parameters such as the one below...

for (i in window.getSelection().getRangeAt(0)) {alert('i = '+i);}

Also there is a VERY nasty range bug in Gecko browsers (e.g. Firefox) where if you move the mouse just slightly outside of an element though less then 50% of a letter/character that Gecko incorrectly sets the boundary element to that element even though it hasn't been selected. It's exceptionally nasty just trying to figure out what it is and Mozilla has actually refused to fix it (as they have with numerous other bugs where they are clearly in the wrong), here is the link for the bug post I made...

https://bugzilla.mozilla.org/show_bug.cgi?id=696571

Hopefully this will get you moving in the right direction.

like image 108
John Avatar answered Oct 04 '22 16:10

John