onfocus selects a [contenteditable]

A requestAnimationFrame() or setTimeout() is necessary unfortunately.

by Ico Dimchev

HTML

<script src="https://gist.github.com/rudiedirkx/5257693/raw/eb27f73ed3b6e9b865eee1a336faf714094168d7/requestAnimationFrame.js"></script>
<p class="focus"><span contenteditable class="input">Wheeeeee!</span> I just unlocked the superselfish bumbadge on fistfuckers.</p>

<p>Focus the greyish <code>[contenteditable]</code> above. It works because of the <code>requestAnimationFrame()</code>.</p>

CSS

.focus {
    margin: 20px;
    border: solid 20px #ddd;
    padding: 20px;
    line-height: 1.45;
}

[contenteditable] {
    padding: 2px 3px;
    background: #eee;
}

JavaScript

document.querySelector('.input').onfocus = function(e) {
    var el = this;
    requestAnimationFrame(function() {
        selectElementContents(el);
    });
};

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}