Every blog has a search bar. The search bar is a typically boring affair, with a white background and a button saying “Search,” and worst of all, it takes up a fair bit of room in your sidebar. Why not use a little Javascript to liven things up and save space? This effect can be seen in use on the search bar to your right.

NB – This method is primarily for WordPress, but could be easily adapted to any other platform.

1 – Find The Default Search bar.

The code for your search bar usually lies in searchform.php, or in functions.php if it has been set up as a widget, and will look as follows:

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div><input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>

The line that we will be changing is this one:

<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />

2 – Display the “Search…” text by default.

To save space that would otherwise be used by a “Search” header, or writing “Search” on the button, we will have this text shown inside the actual search form.

The exception to this is if the user has already used the search function, and is on a search results page. In this case, we would want their search term to be displayed. This effect will be achieved using some basic PHP, and one of the WordPress’s conditional tags.

<input type="text" value="<?php if(is_search() ) { the_search_query(); } else { echo 'Search...'; } ?>" name="s" id="s" />

3 – Adding the Javascript Effects

When a user selects the search bar, we don’t want them to have to remove the default text themselves. Furthermore, if they click out of it again, we will only re-enter the “Search…” text if they did not type anything. Otherwise, their unfinished query will be left as it is.

<input type="text" value="<?php if(is_search() ) { the_search_query(); } else { echo 'Search...'; } ?>" name="s" id="s" onfocus="if(this.value=='Search...')this.value='<?php the_search_query(); ?>'" onblur="if(this.value=='')this.value='Search...'" />

4 – The Complete Form

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div><input type="text" value="<?php if(is_search() ) { the_search_query(); } else { echo 'Search...'; } ?>" name="s" id="s" onfocus="if(this.value=='Search...')this.value='<?php the_search_query(); ?>'" onblur="if(this.value=='')this.value='Search...'" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>

With your new search form, you can now delete the space-consuming “Search” labels placed around your search bar. The bonus of using this method is that it is an easy way of adding useful interactivity to your website, which your users will appreciate.

Enjoy this post? You should follow me on Twitter!