Search code examples
jqueryrangeslicegetselection

window.getSelection().getRangeAt() not working properly


I am trying to get the text selection within a an html element and then insert span tags around it. So far, I am having problems with the correct indices. If I highlight text inside a <p> block, the index goes to 0 after a <br> tag. I want to be able to slice() the text out and then recombine it with span tags after highlighting the text as well as grabbing the selected text and sending it to server via Ajax.

Here is some sample HTML and code:

<html><body><p>This is some sample text.<br>Select this text.</p></body></html>

jQuery:

$('*').mouseup(function() {
    mouseDown = false;

    var startIndex = window.getSelection().getRangeAt(0).startOffset;
    var endIndex = window.getSelection().getRangeAt(0).endOffset;
    alert($(body *).text().slice(startIndex, endIndex));
});

Solution

  • Well i had a look at your code on jsfiddle and the problem seemed to be that javascript didn't know what "highlightedElement" was so i mocked a little demo up for you on jsfiddle....

    It's a bit fragile but it should do what you need it to do: http://jsfiddle.net/WRrH9/5/

    In case it doesn't work for some reason heres your code modified:

    HTML:

    <html>
        <head>
        </head>
        <body>
            <p>This is some sample text.Select this text.
            </p>
        </body>
    </html>​
    

    JavaScript:

    $('body *').mouseup(function() {
        mouseDown=false;
        var startIndex = window.getSelection().getRangeAt(0).startOffset;
        var endIndex = window.getSelection().getRangeAt(0).endOffset;
        var slicedText = $(this).text().slice(startIndex, endIndex);
        $(this).html($(this).text().replace(slicedText,'<span>' + slicedText + '</span>'));
    });​
    

    Hope this helps!