Skip to content

Instantly share code, notes, and snippets.

@nuxodin
Last active August 29, 2015 14:22
Show Gist options
  • Save nuxodin/b02064610abf93dab8c6 to your computer and use it in GitHub Desktop.
Save nuxodin/b02064610abf93dab8c6 to your computer and use it in GitHub Desktop.
WebKit bug workaround: outside click of inline or floated contentEditable-elements focuses the element
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>WebKit bug workaround: outside click of inline or floated contentEditable-elements focuses the element</title>
<script>
if (/AppleWebKit\/([\d.]+)/.exec(navigator.userAgent)) {
document.addEventListener('DOMContentLoaded', function(){
var fixEl = document.createElement('input');
fixEl.style.cssText = 'width:1px;height:1px;border:none;margin:0;padding:0; position:fixed; top:0; left:0';
fixEl.tabIndex = -1;
var shouldNotFocus = null;
function checkMouseEvent(e){
if (e.target.isContentEditable) return;
var range = document.caretRangeFromPoint(e.clientX, e.clientY);
var wouldFocus = getContentEditableRoot(range.commonAncestorContainer);
if (!wouldFocus || wouldFocus.contains(e.target)) return;
shouldNotFocus = wouldFocus;
setTimeout(function(){
shouldNotFocus = null;
});
if (e.type === 'mousedown') {
document.addEventListener('mousemove', checkMouseEvent, false);
}
}
document.addEventListener('mousedown', checkMouseEvent, false);
document.addEventListener('mouseup', function(){
document.removeEventListener('mousemove', checkMouseEvent, false);
}, false);
document.addEventListener('focus', function(e){
if (e.target !== shouldNotFocus) return;
if (!e.target.isContentEditable) return;
document.body.appendChild(fixEl);
fixEl.focus();
fixEl.setSelectionRange(0,0);
document.body.removeChild(fixEl);
}, true);
});
}
function getContentEditableRoot(el) {
if (el.nodeType === 3) el = el.parentNode;
if (!el.isContentEditable) return false;
while (el) {
var next = el.parentNode;
if (next.isContentEditable) {
el = next;
continue
}
return el;
}
}
</script>
</head>
<body>
<div style="padding:0 20px 20px 20px">
<div contenteditable="true" style="float:right; border:1px solid red; margin:10px; width:99%">
this is a content-editable-span, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
</div>
<div contenteditable="true" style="float:left; border:1px solid red; margin:20px; width:99%;">
this is a content-editable-span, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
</div>
<div>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment