简体   繁体   中英

detection of selected text not working properly

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM