bblocs3141
bblocs3141

Reputation: 133

Range text is same after deselect in contenteditable

I have a "mouseup" event handler inside a contenteditable to check wether text has been selected or not. If you highlight text after typing, all is good, but if you click again (to deselect text) the console shows that range.toString() is the same despite no text being selected.

http://jsfiddle.net/xpvt214o/857876/

type something in the contenteditable, then select it, then click again (to deselect) and check the console. Both console.logs will be the same.

I need to differentiate between a real selection and a deselection. If this is normal behavior, how can I tell the two events apart, or how can I do it differently to prevent this behavior?

Upvotes: 1

Views: 182

Answers (2)

Sulokit
Sulokit

Reputation: 137

Please check if this helps.

$('#container').mouseup(function() {
  console.log(getSelectedText());
});

function getSelectedText() {
  if (window.getSelection) {
    return window.getSelection().toString();
  }
  return '';
}

Upvotes: 0

Kaiido
Kaiido

Reputation: 136986

Indeed, Chrome does change the active selection after the mouseup event.

You could add an hackish timeout to this event, which might break some times...

Or you could use the Selection API's selectionchange event.

This event will fire every time the selection does change:

$(document).on('selectionchange', function() {
  console.log(getSelection().toString());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="container">Select this dummy text</div>

Added benefit is that it will also work for keyboard selections.

And to get whether this event was a selection or an unselection, you can check if the content of the selection is empty, or if the current range is collapsed:

$(document).on('selectionchange', function() {
  var isUnselect = getSelection().getRangeAt(0).collapsed;
  viewer.style.backgroundColor = isUnselect ? 'red' : 'green';
})
#viewer{
  width: 20px;
  height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="viewer"></div>
<div contenteditable="true" id="container">Select this dummy text</div>

Upvotes: 2

Related Questions