Question

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));
});
Was it helpful?

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!

OTHER TIPS

Range boundary offsets are relative to the innermost node containing the range boundary, so what you're attempting will not work in the general case.

You may find one of the commands available via document.execCommand() will do the job. Failing that, if you want to keep formatting such as line breaks, this is a non-trivial task as you'll need to surround every text node within the selection inside <span> tags. If your spans have particular CSS classes then you may be able to use the CSS class applier module of my Rangy library.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top