user1721135
user1721135

Reputation: 7092

Only focus on contenteditable when the element is clicked?

It seems with contenteditable you get the focus wherever you click on the page.

How can I make the focus only when the element it self is clicked, but not outside the element?

See demo: http://jsbin.com/iTEkUKa/1/edit

Try to click outside any of the boxes, it still results in focus, thats the problem.

Upvotes: 2

Views: 1090

Answers (1)

Hans Gustavson
Hans Gustavson

Reputation: 166

Use this script:

It works easily explained like that:

On click outside a contenteditable-element get the contenteditable-element that will be focused.
If, on the following focus event, this element gets the focus, remove it.

https://gist.github.com/nuxodin/b02064610abf93dab8c6

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;
    }
}

Upvotes: 2

Related Questions