HTML Content Editable div: select text event

10,173

Solution 1

you could try something like this:

There is no 'selectend' event but we can work out when the user has finished selecting by watching the mouseup event

$(function () {
    $('.editable').on('selectstart', function () {
        $(document).one('mouseup', function() {
            alert(this.getSelection());
        });
    });
});​

Solution 2

Following the answer by @Elliot and the comment by @Michael Bates, this seems to work flawlessly for both mouse and keyboard selection events (example is in TypeScript):

export function attachSelectionListener(element: HTMLElement) : void {
  if (!element.contentEditable) {
    return;
  }
  element.onselectstart = () => handleSelectionChange(element);
}

function handleSelectionChange(element: HTMLElement): void {
  document.onmouseup = () => retrieveSelection(element);
  document.onkeyup = () => retrieveSelection(element);
}

function retrieveSelection(element: HTMLElement) : void {
  const selection = document.getSelection();

  // Ignore empty selection
  if (!selection || !selection.toString()) {
    return;
  }
  alert(selection.toString());
}

When using this in your app, you probably want to check if you need to remove the listeners again at some point.

Share:
10,173
unni
Author by

unni

Updated on July 19, 2022

Comments

  • unni
    unni almost 2 years

    I have a div which is contenteditable

    <div class="editable" contenteditable="true"></div>

    The user can enter any content in there. Is there any way to get the event for when a user makes a selection within the div.

    Something like:

    $('.editable').onSelection(function(e, selection){alert(selection);}
    
  • nevf
    nevf about 10 years
    on.select does not fire for contenteditable. ref: "This event is limited to <input type="text"> fields and <textarea> boxes."
  • Michael Bates
    Michael Bates about 10 years
    You might also want to add keyup in the same event handler as mouseup so that selecting text with the keyboard also works
  • 3limin4t0r
    3limin4t0r almost 2 years
    You'll probably want to use addEventListener(), because assigning element.on{event} = could remove another event. If a user is unaware that attachSelectionListener() sets onselectstart, onmouseup, and onkeyup they might even overwrite the listener themself by accident.