Bananakilo
Bananakilo

Reputation: 1423

selection change event in contenteditable

My markup for contenteditable element is as below:

<iframe class="rich_text">
<html style="background:none transparent;">
    <head></head>
    <body contenteditable="true"></body>
</html>
</iframe>

Is there a selection change event for the body (contenteditable)? So that I can detect whether the selected text block has bold/underline etc.

I've tried some event handlers (jQuery) but without success:

var richText = $(".rich_text"),
richTextDoc = richText.contents()[0],
richTextBody = richText.contents().find("body");

// Enable Design mode.
richTextDoc.open();
richTextDoc.write("");
richTextDoc.close();
richTextDoc.designMode = "on";

// Binds selection change event
$(richTextDoc).bind("select", function() { ... });
$(richTextDoc).bind("selectstart", function() { ... });
richTextBody .bind("select", function() { ... });
richTextBody .bind("selectstart", function() { ... });

Upvotes: 7

Views: 10816

Answers (3)

Tim Down
Tim Down

Reputation: 324727

Update 2017+

There is now a cross-browser way. Recent WebKit/Blink browsers (Chrome, Safari, Opera) support selectionchange, and Firefox supports it since version 43.

Old Answer

There is no cross-browser way of detecting changes to the selection. IE and recent WebKit browsers (Chrome and Safari, for example) support a selectionchange event on the document. Firefox and Opera have no such event and all you can do is detect selection changes made via keyboard and mouse events, which is unsatisfactory (there is no way of detecting "Select All" from context or edit menus, for example).

Upvotes: 7

dos
dos

Reputation: 11

for firefox, https://developer.mozilla.org/zh-CN/docs/XPCOM_Interface_Reference/NsIEditor, offers OBSERVER on editors. Assumingly 'privileges' are needed as XPCOM-based. Other sol. on firefox beside mouse & kbd-tracking:

on 'focus' and 'blur' - events of all/concerning nodes/elements(text?) compare the node-content between state at focus-event and the node-content at the blur-event (= leave, also if window-close or sop'n similar), and set YOUR, or '_moz_dirty' , dirty-attribute(s. depending on whom/what browser it should serve, make also MANY different dirty-attrib's as purposes are requiring).

Upvotes: 1

mamoo
mamoo

Reputation: 8166

Assuming that the content of your iframe is served from the same domain you could use:

$('.rich_text').contents()
  .find('body')
  .bind('selectstart', function(){});

As you can see from here, the selectstart event is correctly fired when the element is selected.

Upvotes: 5

Related Questions