Reputation: 908
I have a div with [contenteditable=true]
attribute. When I select some text and click a button, I want to get the selected text. I did the following:
$(".btn").click(function (){
alert(window.getSelection());
});
The above code does not alert anything. If I change the .btn
element to an img
element, the alert outputs the selected text. What can I do to get selected text on click of any element
Thid is my html code:
<li class="btn">Selection </li>
<div contenteditable="true">Some text here</div>
Upvotes: 1
Views: 335
Reputation: 204
<script language=javascript>
function getSelText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
}
else if (document.getSelectiion) {
txt = document.getSelection();
}
else if (document.selection) {
txt = document.selection.createRange().text;
}
else return;
alert(txt)
}
window.document.onmousedown = function() {
getSelText()
}
</script>
Upvotes: 1
Reputation: 813
When you select your required text and click the button, as Ramon & adeneo explains in his comment, the focus is lost. Button command is executed at mouseup
at which point the selection is cleared. As far as I understand, the reason why your code works with an image because unlike a button the image command is executed at mousedown
.
My suggestion would be to try an .on('mousedown', ...)
command instead of a simple click command.
Upvotes: 3