简体   繁体   中英

HTML Content Editable div: select text event

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);}

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());
        });
    });
});​

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.

$('#ta').select(function() {
alert('Handler for .select() called.');
});

.select( handler(eventObject) ) Returns: jQuery Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

.select( handler(eventObject) ) handler(eventObject)A function to execute each time the event is triggered.

.select( [eventData], handler(eventObject) ) eventDataA map of data that will be passed to the event handler. handler(eventObject)A function to execute each time the event is triggered.

check link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM