<input type=search>
is one of the HTML5 additions to form input types. In theory you can just replace the old <input type=text>
with the new type and browsers continue to work and the site is now more semantic. In practice working with type=search
is not that simple.
First thing you probably want to do is to remove Webkit’s default, heavy styling. You do that by these CSS commands:
-webkit-appearance:textfield; -webkit-box-sizing:content-box;
I initially used the former, but after some odd width calculation issues I found out that latter is also needed to actually fully restore familiar type=text behavior.
Placeholder text is another wonderful addition to input elements (not just type=search). This replicates the common behavior of having the search field label within the field itself (until the user focuses the field). You add placeholder text by adding an attribute to the input element like this: placeholder=”search this site”.
To gracefully degrade, use Modernizr to detect a browsers with no support:
jQuery(function($) {
if (!Modernizr.input.placeholder || navigator.userAgent.match(/opera/i)) {
$('input[placeholder]').hint();
}
});
Here I decided to replace native placeholder support on Opera, since there are no styling options for it, yet. The text is always in #7f7f7f
, which was not an option, since the background was exactly that color.
To style placeholder text you need these rules:
input[type=search].blur{color:#ddd}
input[type=search]::-webkit-input-placeholder{color:#ddd}
input[type=search]:-moz-placeholder{color:#ddd}
You cannot combine those selectors, since the rule will stop working as expected. .blur is for browsers that do not support native placeholder behavior.
And here is the modified version of the plugin that adds placeholder behavior. To make it more HTML5 friendly, I basically just replaced the use of title attribute with placeholder attribute.
/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
* Modified to use placeholder attribute by Aki Björklund, https://akibjorklund.com/
*/
(function ($) {
$.fn.hint = function (blurClass) {
if (!blurClass) {
blurClass = 'blur';
}
return this.each(function () {
// get jQuery version of 'this'
var $input = $(this),
// capture the rest of the variable to allow for reuse
placeholder = $input.attr('placeholder'),
$form = $(this.form),
$win = $(window);
function remove() {
if ($input.val() === placeholder && $input.hasClass(blurClass)) {
$input.val('').removeClass(blurClass);
}
}
// only apply logic if the element has the attribute
if (placeholder) {
// on blur, set value to placeholder attr if text is blank
$input.blur(function () {
if (this.value === '') {
$input.val(placeholder).addClass(blurClass);
}
}).focus(remove).blur(); // now change all inputs to placeholder
// clear the pre-defined text when form is submitted
$form.submit(remove);
$win.unload(remove); // handles Firefox's autocomplete
}
});
};
})(jQuery);