How to simulate Highlighting text when Double Click with single Click Event

961 Views Asked by At

I want to simulate the highlight action on selected text when i double click on the text, but with just a single click event. How can i do it? I tried with these code but fail

handleOnClick(event) {
  event.preventDefault();

  //i thought this suppose to trigger double click event 
  //and highlight the text under the mouse cursor
  event.target.dispatchEvent(new MouseEvent('dblclick', {bubbles:true}));

  //...
}
1

There are 1 best solutions below

1
On

Do you need the whole div element or just some part of it? Here's a solution to highlight the whole div on double click event.

HTML
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Highlight</title>
    </head>
    <body>
      <div id="text">Text to be highlighted</div>
    </body>
    </html>
CSS
    .highlight {
      background: yellow;
    }

JS
document.querySelector('#text')
  .addEventListener('dblclick', () => {
  document.querySelector('#text').classList.add('highlight');
});