Chrome contentEditable div blur bug
by Marek Suscak
HTML
<p>Edit the text below and then hit "Enter" or "ESC" to lose focus.</p>
<div class="editable" contenteditable="true">Text</div>
CSS
html, body {
font: 14px arial, sans-serif;
padding: 2em;
}
p {
margin: 0 0 2em 0;
}
div {
background: #eee;
box-sizing: border-box;
border: 1px solid transparent;
opacity: .55;
padding: 5px;
width: 200px;
transition: all .5s ease;
}
div:hover {
border: 1px solid #ddd;
opacity: 1;
}
div.focus {
box-shadow: 0 0 10px rgba(26, 154, 245, .5);
border: 1px solid #1a9af5;
outline: 0px solid transparent;
}
JavaScript
$(".editable").bind("keydown", function(event) {
var target = $(event.target);
c = event.keyCode;
if(c === 13 || c === 27) {
$(".editable").blur();
// Workaround for webkit's bug
window.getSelection().removeAllRanges();
}
});
$("[contenteditable='true']").on("focus", function() {
$(".editable").toggleClass("focus");
});
$("[contenteditable='true']").on("blur", function() {
$(".editable").toggleClass("focus");
});