For the longest time, I’ve always had to search far and wide for a single small snippet of code that allows the following in a text input box:
- Default text that is displayed
- When the user clicks in the text box, the text is cleared out only leave the precursor
- If the user does not type anything and clicks away, it resets back to the default value
This technique uses two simple html attributes. ‘onblur’ and ‘onfocus’. This is most commonly associated with a search box and adds that final spice to a website. Here is the code, free of charge.
1 2 3 4 5 6 7 8 | <form method="post" id="searchform" action="/"> <fieldset> <label>Search:</label> <input type="text" onblur="if (this.value == '') {this.value = 'Search...';}" onfocus="if (this.value == 'Search...') {this.value = '';}" value="Search..." name="s" /> </fieldset> </form> |
So what exactly IS onblur and onfocus? Javascript, default browser actions, and some super cool tricks. Let me explain…
The definition of “onblur” is “The onblur event occurs when an object loses focus”. An object is focused when you have it selected. For example, on the right hand of the screen near the top is our search box. If you click INSIDE of that box, your cursor is now placed inside and will have SELECTED that box. Upon SELECTING that box, it will activate the opposite of “onblur” which is “onfocus”. The event that is fired off when clicking or “focusing” in an object on the page is called “onfocus” and when clicking on any other object, which will deselect the currently selected object in favor for another is called “onblur”. Just think of a microscope zooming in and out of a 3-D page.
“I get how and why, but why is there a <fieldset> and <label> in there” you say? It’s for XHTML validation purposes. Always remember to have a Label for a form, and to wrap it in a fieldset if there are multiple forms on a page for maximum compatibility for different browsers and mobile devices.
Recent Comments