0

I am struggling to find a Javascript event for when the user highlights paragraph text on a web page with the mouse. Once the text is highlighted, I can get to it with window.getSelection().

This is not about trapping events within an <input type="text"> or <textarea>, that is easy.

I'm interested in when the user highlights text that would be controlled with the CSS user-select: all; or user-select: none;.

Bonus for a jQuery answer. ;-)

mike
  • 1,951
  • 18
  • 26

2 Answers2

0

Just use the select event.

Example shamelessly copied from MDN:

function logSelection(event) {
  const log = document.getElementById('log');
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  log.textContent = `You selected: ${selection}`;
}

const input = document.querySelector('input');
input.addEventListener('select', logSelection);
<input value="Try selecting some text in this element.">
<p id="log"></p>
D. Pardal
  • 5,634
  • 1
  • 15
  • 34
-1

You can bind to mouseup:

<body>
<div style='user-select: all'>
  all all all all all all all all all all all 
</div>
<br>
<div style='user-select: none'>
  none none none none none none none none none 
</div>
<br>
<div style='user-select: text'>
  text text text text text text text text text
</div>  
</body>
<script type="text/javascript">
document.addEventListener('mouseup', event => {
    if( window.getSelection().toString().length){
        window.alert (window.getSelection().toString());
        window.getSelection().empty();
    }
})
</script>
clamp
  • 2,212
  • 1
  • 4
  • 15