Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force contenteditable div to stop accepting input after it loses focus under Webkit

In Chrome and Safari (and possibly other Webkit based browsers) it's still possible to type in a contenteditable div, even after the div loses focus.

I built a simple example to illustrate this issue: http://jsfiddle.net/yfcsU/3/

The example has two elements: a div with contenteditable="true" and a link that will trigger a blur event on the contenteditable div when it's clicked.

When the link is clicked, the contenteditable div loses focus but you're still able to type in the div and any keypress will cause it to re-focus.

This behavior is different in Firefox where it works as expected: clicking the link will cause the contenteditable div to stop accepting input.

In Webkit, is there a way to force the contenteditable div to stop accepting input after it loses focus without disabling contenteditable on the div?

like image 857
dcro Avatar asked Sep 10 '12 13:09

dcro


2 Answers

Answer marked as correct is in fact correct but I would add another solution that may be a little bit more straightforward. After you call blur() on the contentEditable div you have to call this:

window.getSelection().removeAllRanges();

Test here: http://jsfiddle.net/mareksuscak/oytdoxy8/

Seems to me that it does the same job and also explains why it does not work correctly - usually selection range is removed from input elements when blurred but it somehow does not get executed for contentEditable divs and thus after entering any character/libe break it is focused again.

like image 180
Marek Suscak Avatar answered Nov 16 '22 21:11

Marek Suscak


After struggling with this for a while, I was albe to find a way to force a contenteditable element to stop accepting input on Webkit.

The solution is to create a temporary editable element, add it to the DOM, focus it and then remove it. This will cause any other contenteditable element on the page to deactivate itself.

The equivalent jQuery code for this would be:

$('<div contenteditable="true"></div>').appendTo('body').focus().remove()

I've updated the original example to include a demo of this technique: http://jsfiddle.net/yfcsU/4/

like image 31
dcro Avatar answered Nov 16 '22 22:11

dcro