Search code examples
webkitcontenteditable

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?


Solution

  • 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.