Autofocus without Killing Placeholder
by b9chris
HTML
<input id=Url />
<p>
Test typing first key in body, redirected to input box, without autofocus killing placeholder in Chrome etc.
</p>
JavaScript
var urlInput = $('#Url');
function bodyFirstKey(ev) {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
if (ev.target == document.body) {
urlInput.focus();
if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {
urlInput.val(ev.key);
return false;
}
}
};
function urlInputFirstFocus() {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
};
$('body').keydown(bodyFirstKey);
urlInput.focus(urlInputFirstFocus);