Reputation: 9065
I am trying detect, with javascript, if a text inside a div
formatted as a textarea
is selected or not. The HTML is this:
<div id="rte-test" class="rich-text-editor">
<ul class="toolbar">
<li> <a href="#" class="command" id="...">...</a> </li>
</ul>
<div class="textarea" id="textareaContent" contentEditable="true"></div>
</div>
I tried this javascript code:
var command = document.getElementsByClassName("command");
for(var i=0; i<command.length; i++) {
command[i].addEventListener("click", function() {
var btn = this;
var content = window.document.getElementById("textareaContent");
if (content.getSelection) {
console.log(content.getSelection() + ' selected. ' + btn.id);
} else {
console.log('nothing is selected. ' + btn.id);
}
});
}
with this code only the "nothing is select" option is reached by the if/else
even if something is selected on the textarea
.
I also tried this:
var command = document.getElementsByClassName("command");
for(var i=0; i<command.length; i++) {
command[i].addEventListener("click", function() {
var btn = this;
if (window.getSelection) {
console.log(window.getSelection() + ' selected. ' + btn.id);
} else {
console.log('nothing is selected. ' + btn.id);
}
});
}
with this code only the "selected" option is reached by the if/else
even if nothing is selected.
Anyone have any idea of how to fix that?
Upvotes: 0
Views: 35
Reputation: 342
try
if (window.getSelection().toString()) {
console.log(window.getSelection() + ' selected. ' + btn.id);
} else {
console.log('nothing is selected. ' + btn.id);
}
window.getSelection()
returns a non empty object which will always be true as it is not empty. When you put window.getSelection()
into console.log
, toString()
is automatically called.
Upvotes: 2