Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Selected Text In ContentEditable DIV?

So I have a contenteditable div in my Rails app, and need to be able to display a little popup above text when it's highlighted. Currently I have code that works, and it displays the highlighted text in an alert. However, the function executes on mouseup, so when you click into the div to start typing or highlighting, it throws an empty alert.

Here's my code:

function getSelected() {
            if (window.getSelection) {
                return window.getSelection();
            }
            else if (document.getSelection) {
                return document.getSelection();
            }
            else {
                var selection = document.selection && document.selection.createRange();
                if (selection.text) {
                    return selection.text;
                }
                return false;
            }
            return false;
        };
$("#content-create-partial").bind("mouseup", function(){
                var text = getSelected();
                if(text) {
                    console.log(text);
                }
                else{
                    console.log("Nothing selected?");
                };
            });

How do I prevent jQuery from executing the function when the user clicks into the contentEditable div? I only want it to execute when actual text is highlighted.

like image 956
Tom Maxwell Avatar asked Aug 26 '13 00:08

Tom Maxwell


2 Answers

Try this

window.getSelection().anchorNode.data.substring( window.getSelection().anchorOffset,window.getSelection().extentOffset )

Try Working Exmaple Here.

like image 182
Training at Manorama Avatar answered Nov 13 '22 10:11

Training at Manorama


You can simply check if the Selection.toString() method returns an empty string

if(window.getSelection().toString()){
    // do something
}
like image 36
Mendy Avatar answered Nov 13 '22 09:11

Mendy