luminescente

input type=search - Extreme overhauling

Programming, Projects — Pedro Cardoso on March 26, 2006 at 6:38 pm

If you’re using Apple’s Safari browser, you may have noticed the following input element, similar to a text box.

Safari Input Search

This element was introduced with Tiger (Mac OS X 10.4) integrated with Dashboard and Safari RSS, but it soon started to appear in some other sites. At it’s heart, this is just a special kind of INPUT element, of type “search”, that Safari renders as a Cocoa search field. Other browsers that don’t know what it is (ie, everyone else) default to a normal textbox, with no ill effects, apart from failing validation.

There are several new attributes for this element, documented here, but in short:

  • placeholder: the text to be shown in light gray when the box is empty
  • autosave: the identifier for auto saving entered values
  • results: the number of auto saved searches

What if there was a way to have this kind of element rendering in the other browsers like it does in Safari?

Well, I hacked away and now there is. I’ve been wanting to wait a little more and clean up the code but release early and release often, right? :)
Just include the code at the end of this post in your HTML, and that’s all, your search input elements will become like this in other browsers.

Input Search Test

Under the hood

At startup, all the INPUT elements of type search are parsed and this happens:

  • The element we are messing with is hidden, and a new container SPAN is created containing (in this order) the search image, a new textbox and the clear button. These elements are styled to look like a single element. In Mozilla, the corners are rounded using the -moz-corner-radius CSS rule.
  • The onBlur/onFocus events are defined so we can automatically clear and set the textbox’s default message (using the attribute placeholder)
  • Similar monkey business is done to the onChange so we can show/hide the clear button when appropriate.

Notes: This behaviour can be easily modified to apply this hack to elements with a certain className, instead of applying to elements of input type=search. When in the presence of Safari, replace the text with a search input. This way the (X)HTML could remain standards-compliant.

This code is yours to do as you please, just leave a comment if you like it… :)

    Todo
  • Re-use the text element instead of creating a new one and hiding the old one.
  • Paste-aware
  • Implement auto saving (using client-side cookies?)
  • Improve the positioning of the images

The files are here. You need the HTML along with the image files.

0 Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. | luminescente