Reputation: 9573
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
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
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