Search code examples
javascriptace-editor

ACE editor get selected word after double click


When I double-click on a word, I would like to get that word.

    editor = ace.edit("code_editor");
    editor.on('dblclick', function() {
        var selected_word = editor.getSelectedText()
    });

I can detect double-click with the code above. However, selected word is always empty. It is too fast, and does not allow a complete word to get selected. What is the solution here?


Solution

  • Your assumption was right it was too fast. I've tried to delay the selection grab and it worked fine using this:

    editor.on("dblclick", function () {
        setTimeout(() => {
            var selected_word = editor.getSelectedText();
            console.log(selected_word);
        }, 10);
    });
    

    And that solved the issue

          var editor = ace.edit("editor");
          editor.on("dblclick", function () {
            setTimeout(() => {
              var selected_word = editor.getSelectedText();
              console.log(selected_word);
            }, 10);
          });
          #editor {
            position: absolute;
            width: 500px;
            height: 400px;
          }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Ace Editor</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
      </head>
      <body>
        <div id="editor">
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusantium
          expedita porro doloremque error, nobis dignissimos ducimus quidem. Quo
          cumque pariatur debitis laborum, minus magnam enim, repudiandae omnis iste
          cupiditate culpa.
        </div>
      </body>
    </html>

    Added working code snipet