jQuery enhanced search field

Similar effects could be created purely with CSS.

by Jennifer Perrin

HTML

<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
<form action="" method="get">
    <fieldset>
        <input type="text" id="searchbar" />
        <input type="submit" value="Search" id="searchbtn" />
    </fieldset>
</form>

<p>Similar effects could be created purely with CSS. There’s the pseudo <code>:focus</code> selector which allows us to add special styling to elements when they have the user’s attention. Plus, the default input value could be added as a background image, which is then removed also using the <code>:focus</code> selector. But there’s two small problems; firstly the <code>:focus</code> selector isn’t supported by Internet Explorer, and secondly there’s no way of ensuring the default value doesn’t reappear once the user has entered their own information within the input field. This is where jQuery takes over to provide a complete solution that’s compatible with all browsers.</p>

CSS

body, div, form, fieldset, input {
    margin: 0; 
    padding: 0; 
    border: 0;
}

body {
    background: url("http://jenniferperrin.com/image/background.gif");
    line-height: 10px;
}

p {
    width: 625px;
    margin: 10px auto;
    line-height: 20px;
    color: #efefef;
}
code {
    background: none repeat scroll 0 0 #444;
    padding: 1px 5px;
}

form {
    width: 625px;
    margin: 40px auto;
}

#searchbar {
    width: 425px; 
    float: left; 
    padding: 5px;
    background: #efefef;
    border: 3px solid #d79800;
    border-radius: 100px; 
    -moz-border-radius: 100px; 
    -webkit-border-radius: 100px;
    font: italic 16px Georgia;
    color: #444;
    outline: none; /*Remove Chrome and Safari glows on focus*/
}    
#searchbar.active {
    background: #ebf3fc;
    border: 3px solid #d46a15;
}

#searchbtn {
    width: 16px; 
    height: 16px; 
    float: left; 
    margin: 8px 0 0 -30px;
    background: url(http://jenniferperrin.com/blog/wp-content/themes/artisan/images/icons/search_16.png) no-repeat;
    text-indent: -9999px;
    padding: 0 0 0 67px; /*IE fix*/
    cursor: pointer;
}

JavaScript

$(document).ready(function() {
    $("#searchbar").attr("value", "I'm looking for...");
    
    var text = "I'm looking for...";
    
    $("#searchbar").focus(function() {
        $(this).addClass("active");
        if($(this).attr("value") == text) $(this).attr("value", "");
    });
    
    $("#searchbar").blur(function() {
        $(this).removeClass("active");
        if($(this).attr("value") == "") $(this).attr("value", text);
    });
});