16

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;
    }
}

$("#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.

Jo Liss
  • 30,333
  • 19
  • 121
  • 170
Tom Maxwell
  • 9,273
  • 17
  • 55
  • 68

6 Answers6

6

You can compare window.getSelection().anchorOffset and window.getSelection().extentOffset to see if they are equal. If they are, then it was just a normal click.

Tarun Dugar
  • 8,921
  • 8
  • 42
  • 79
5

Try this

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

Try Working Exmaple Here.

3

The following will return true if nothing is selected.

Inspired from @Tarun Dugar. But didn't work in all browsers. The following worked.

window.getSelection().focusOffset == window.getSelection().anchorOffset;
Pang
  • 9,564
  • 146
  • 81
  • 122
3

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

if(window.getSelection().toString()){
    // do something
}
Mendy
  • 7,612
  • 5
  • 28
  • 42
0

There is "selectstart" event which fires when user starts selection. There is no selection end event but you can listen for mouseup event after "selectstart" event fired to make sure selection has occurred.

Edit:

Check - HTML Content Editable div: select text event

Community
  • 1
  • 1
DexTer
  • 2,043
  • 1
  • 22
  • 45
-2

Just check if the selection is empty: if ($.trim( text) != '') ...

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
hammett
  • 705
  • 4
  • 13