Google Chrome and Safari (WebKit) bug with the HTML5 autofocus attribute

I just encountered the weirdest bug with the HTML5 autofocus attribute in Google Chrome and Safari.

Bug description

When using the autofocus attribute in a web page, when using JavaScript to change the CSS of a sibling element, it will not render in Google Chrome 7 and later and Safari 5 (haven’t tested older versions of either).

Prerequisites

A number of certain factors need to be met to encounter this behavior:

  • An input element with the autofocus attribute.
  • Two sibling elements to the one with the autofocus attribute: one visible which will, when clicked, display the other element.
  • The CSS code has to be included via a link element – if it’s within the web page in a style element, all will work fine.
  • The page will work the first time it’s loaded, but will fail after a soft reload.

Code being used

This is the code needed to trigger this bug:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Test case: autofocus attribute</title>
	<link rel="stylesheet" href="autofocus.css">
	<script>
		window.addEventListener("DOMContentLoaded", function () {
			var help = document.getElementById("help"),
				helpInfo = document.getElementById("help-info");
	        if (help && helpInfo) {
	            help.addEventListener("click", function (evt) {
	                helpInfo.className = "show";
	                evt.preventDefault();
	            }, false);
			}
		}, false);
	</script>
</head>

<body>

	<h1>autofocus bug</h1>
	<p>The question mark will be unable to show the help information element, given a few criteria:</p>
	<ul>
		<li>
			An <code>input</code> element with the <code>autofocus</code> attribute.
		</li>
		<li>
			Two sibling elements to the one with the <code>autofocus</code> attribute: one visible which will, when clicked, display the other element.
		</li>
		<li>
			The CSS code has to be included via a <code>link</code> element - if it's within the web page in a <code>style</code> element, all will work fine.
		</li>
		<li>
			The page will work the first time it's loaded, but will fail after a soft reload.
		</li>
	</ul>

	<form>
		<input type="text" autofocus> 

		<a href="/" id="help">?</a>

		<div id="help-info">
			<p>Some help information...</p>
		</div>
	</form>


</body>
</html>

CSS

#help-info {
	display: none;
}

#help-info.show {
	display: block;
}

Demo

You can test this behavior in the autofocus test page.

10 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.