HTML and CSS Reference
In-Depth Information
Example 1: Supporting the autofocus attribute
Save Modernizr locally and call it in the
head
of your document:
<head>
<script src="modernizer.js"></script>
</head>
Code your form using the
autofocus
attribute:
<form>
<p><label>Search <input type="search" name="query" id="query"
autofocus></label></p>
<p><button type="submit">Submit</button></p>
</form>
Write a script to detect support for
autofocus
and, if it is not available, use JavaScript
to focus on the element. This script can appear immediately after your form, to trigger
the focus event as quickly as possible:
<script>
if (!Modernizr.input.autofocus) {
document.getElementById("query").focus();
}
</script>
Example 2: Supporting the placeholder attribute
Call Modernizr and jQuery in the
head
of your document:
<head>
<script src="modernizer.js"></script>
<script src="jquery.js"></script>
</head>
Code your form using the
placeholder
attribute:
<form id="search">
<p><label>Search <input type="search" name="query" id="query" value=""
placeholder="Enter query"></label></p>
<p><button type="submit">Submit</button></p>
</form>
Write a script to detect support for
placeholder
and, if it is not available, use JavaScript
to toggle the display of the placeholder text in the input field:
<script>
if (!Modernizr.input.placeholder) {
$("#query").focus(function() {
if ($("#query").val() == $("#query").attr('placeholder')) {
$("#query").val("");
}
});
$("#query").blur(function() {
if ($("#query").val() == "") {
$("#query").val($("#query").attr('placeholder'));
}