Tom Maxwell
Tom Maxwell

Reputation: 9573

Display popup above highlighted text in contenteditable div?

I'm building a simple blogging-esque feature into one of my apps, and use the HTML5 contenteditable attribute because it's clean. However, what I need to do now is when the user highlights some text in the contenteditable div, a popup needs to appear above it. Right now I have a function that gets the selected text, which is binded to the DIV's mouseup(). However, when I click into the contenteditable div, the function is fired.

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 the call from being fired when the user clicks into the contenteditable div, and only when they highlight some text?

Upvotes: 3

Views: 1383

Answers (2)

mbayomi
mbayomi

Reputation: 71

Convert it to a string (.toString()), use trim() in case the selected string is empty and in the mouseup event check the length of the selected string.

 $("#content-create-partial").bind("mouseup", function(){
        var text = getSelected().toString().trim();
        if(text.length>0) {
            console.log(text);
        }
        else{
            console.log("Nothing selected?");
        };
    });

Upvotes: 0

Gopinath G
Gopinath G

Reputation: 97

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


  } 
         });

Upvotes: 2

Related Questions