scala_newbie
scala_newbie

Reputation: 3465

Get the selected text on <p> tag

Using jquery or pure javascript, is there a way to get the currently selected text of a <p> tag? I'm aware of input.selectionStart, but it only exists on <input>.

Upvotes: 4

Views: 1737

Answers (2)

user1858502
user1858502

Reputation:

Here's a simple solution. Works in chrome, safari, FF, and IE9+, but you will have to test on any other legacy browsers you may want to support. http://jsfiddle.net/YEu3k/1/

<p id="pText">here is some text</p>

<script>
    document.getElementById('pText').onmouseup = function(){
        var sel = window.getSelection(), range;
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
            alert(range);
        }
    };
</script>

Upvotes: 5

mattn
mattn

Reputation: 7733

Try to use https://github.com/madapaja/jquery.selection

selection range is different behavior in each browsers. this plugin make commonly interfaces to selection range.

Upvotes: 0

Related Questions