Reputation: 7094
I have some text in div selectable
and I want to allow the user to remove text by selecting the text using their cursor.
It works fine, but if you click on the text, everything is removed. If you click and drag to select, it works fine.
What can I do to make it work with my text properly. If user clicks the text, it shouldn't remove everything.
jsFiddle for testing.
jQuery:
if (window.getSelection().toString() != "") {
selectedText = window.getSelection().toString()
var text1 = $(".selectable").text().split("")
pointStart = window.getSelection().anchorOffset
pointEnd = window.getSelection().focusOffset
if (pointEnd < pointStart) {
pointStart = pointEnd
}
text1.splice(pointStart, selectedText.length);
text1 = text1.join("")
} else {
selectedText = $(".selectable").text()
var text1 = ""
}
$(".selectable").text(text1)
Example HTML:
<div class="selectable">
Hello world what is 進撃の巨人 reality test test... test.
</div>
EDIT: Potential solution:
if (window.getSelection().toString() == "") {
return false;
}
Upvotes: 0
Views: 85
Reputation: 3655
Your error lies on the else
part. If the user has not selected any text, which is the case of simply clicking on the text, your else
code block gets executed.
In that block you assign var text1 = "";
Later you assing text1
as the text content of your $(".selectable")
element.
Just change that line to:
var text1 = selectedText;
See the updated fiddle
I also suggest you declare var text1
only once at the top of your mouseup handler and change your assignments from var text1 = "value"
to text1 = "value"
See: var hoisting
Upvotes: 1