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
  • 2,149
  • 20
  • 29

1 Answers1

-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,552
  • 1
  • 6
  • 16