written on:7 Jan, 2008 by Alen Grakalic

Style Your Website's Search Field with JS/CSS

Delicious Digg StumbleUpon Reddit Subscribe to RSS Feed

search

Continuing to provide unobtrusive solutions, CSSG is happy to present SearchField. It serves as a way to style your search field and add behavior without any additional JavaScript or modifications in your markup. It features plug & play onfocus and onblur behaviors and auto suggestion like you've never seen before :)
Again, all you need is two lines of code, links to JavaScript and CSS files and that would be it.

Take a look at the Demo | Download SearchField

Features

SearchField features 3 states for search input field based on user's actions. We have inactive state, on click state (on focus to be exact) and inactive with user inputted text. You've seen these features on many sites but the difference here is that all you need to do is provide id to your search field, script takes it from there.
Additional feature, that can be turned on and off, is a search suggestion terms displayed as a dropdown box below the search field. You can navigate with up and down keys, or your mouse and you can edit your own keywords. Again, there is a difference between this and other suggestion or autocomplete scripts. With SearchField you don't have to worry about additional markup or id's for dropdown list, it is generated automatically.

Implementation

Download the script, extract the files and place the folder named "searchfield" in the root of your site. Add these two lines of code inside your head tag.

<link href="/searchfield/searchfield.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="/searchfield/searchfield.js"></script>

Now, all you need inside the markup is a search input field with exact id as named in .js file. Default id is "searchfield" but you can use anything.
Important thing is the parent element of the search field. I suggest using <p> tag as a parrent element. Here's how original form looks like, so you can use something similar.

<form id="searchform" action="" method="post">
<p><input type="text" id="searchfield" name="searchfield" value="" />
<button type="submit">Go</button></p>
</form>

At the end modify css file to make it blend into your site.

Files

There are 2 main files, searchfield.js file and searchfield.css. Inside the .js file you can edit 4 parameters and get the results you want. The appearance of your field and dropdown suggestion box is modified via .css file. The class names are commented so you'll find your way around it pretty well.

Parameters

Inside the searchfield.js we have 4 parameters: id, defaultText, suggestion, suggestionText.
First one represents id of the search field you want to add this script to. You can use your own id just make sure that it matches the search field in your html file. defaultText is a text that your search field will use as default value. When you set suggestion=true the script will generate search suggestions list for search field based on content of variable called suggestionText. If you don't want suggestion list to appear set suggestion=false.

Preview and Download

Take a look at the Demo

Download SearchField

Note: since Safari has it's own behaviors for input elements this script is disabled for that browser.

About the author:

cssglobe's image Designer, developer and a passionate standardista. Long time web professional with huge experience in all types of front-end work. Founder of Css Globe and creator of Easy front-end framework.
To get in touch, visit Alen's personal page, follow Alen on Twitter or become a Facebook friend.

Enjoyed the article?

Then don't miss our next one! Subscribe to our RSS feed or share it with your friends.

Delicious Digg StumbleUpon Reddit Subscribe to RSS Feed

Read more! Here are our most recent articles:

View All Articles

Comments

  1. dodot on 9 Jan, 2008 wrote:

    Nice work Alen!
  2. SMASHINGAPPS.COM on 9 Jan, 2008 wrote:

    Great job.
  3. Colin on 9 Jan, 2008 wrote:

    >> When you set suggestion=true the script will generate search suggestions list for search field based on content of variable called suggestionTex

    Where does the autosuggest word list come from? Can you be more descriptive? Does it "automatigicaly learn words" or do you have to create a search term list?
  4. cssglobe on 9 Jan, 2008 wrote:

    You're right Colin. Now that I read it I agree it needs to be clarified. Suggestion terms are hardcoded inside a string variable and separated with comma. This can easily be modified to be an dynamically loaded array or something, but I wanted to provide solution for those who don't know any JavaScript - plain old text.
  5. kyle on 10 Jan, 2008 wrote:

    Works great for firefox on mac, but not in Safari (Leopard, Safari 3.0.4)
  6. kyle on 10 Jan, 2008 wrote:

    Sorry I missed the Note About Safari.
    I wanted to enable this for Safari anyway, and did it by adding the line

    this.safari = false;

    below the line (38)

    this.safari = ((parseInt(navigator.productSub)>=20020000)&&(navigator.vendor.indexOf("Apple Computer")!=-1));

    On searchfield.js
  7. cssglobe on 10 Jan, 2008 wrote:

    or you could commented that line :)
  8. cssglobe on 10 Jan, 2008 wrote:

    I disabled it in safari because I started to work on searchfield as a onfocus and onblur behaviors for inputs and didn't add suggestion box until later.
  9. Moz on 16 Jan, 2008 wrote:

    This is nice work. Thanks
  10. hcabbos on 18 Jan, 2008 wrote:

    Has your example code for the demo been fixed for Safari 'cause I don't see it working.
  11. ovi on 19 Jan, 2008 wrote:

    The keyword list appears ok but under a horizontal CSS menu ( ul and list elements ) .. I will try to fix it. I don't know why is like that :(
  12. ovi on 19 Jan, 2008 wrote:

    I managed to fix the suggestion list appeareance over my menu, but it only works in Opera and FF. I add an zindex:1000 .

    The problem is that the menu loads an htc file in IE (adx.htc) which makes the mouseover work in IE
    ADxMenu behavior - standard - v0.2

    Anybody can give me some hints on this? (I wasnt abble to find anything related to z index in the htc file)

    Thank you.
  13. Marc on 26 Jan, 2008 wrote:

    Nice work...

    and now with german 'umlauts' please :-)
  14. Dragon on 27 Jan, 2008 wrote:

    Very nice. Can you demo the code that would make this dynamically "learn" key phrases? That would make this a perfect solution!
  15. cssglobe on 27 Jan, 2008 wrote:

    @Dragon: There is a way of doing it and I might release a "smart" version of it soon.
  16. Vectorpedia (Rick) on 28 Jan, 2008 wrote:

    Thanks for the great information.......this should help in my web design
  17. meyabilisim on 30 Jan, 2008 wrote:

    Nice work. Thanks so much!
  18. Thomas on 21 Feb, 2008 wrote:

    How do you link to the pages from the a href links in the drop down?
    Cheers
  19. cssglobe on 22 Feb, 2008 wrote:

    Drop down was meant to be suggestion box for search field, not a menu... so, it's purpose is to suggest phrases. To click on one of them means that you want to use that phrase as a search term.
  20. ercan on 27 Feb, 2008 wrote:

    enter is nothing error
    line 179
    for(var i=0;i<li.length;i++){

    :(
  21. Thomas on 3 Mar, 2008 wrote:

    I miss spoke when I asked my previous question, I want to know how to link to a page from the terms that are in drop down when the user presses "go".

    Cheers
  22. Thomas on 3 Mar, 2008 wrote:

    I miss spoke when I asked my previous question, I want to know how to link to a page from the terms that are in drop down when the user presses "go".

    Cheers
  23. Ledzep on 14 Mar, 2008 wrote:

    Hi cssglobe,
    great work, thanx for!
    Question: pressing the "Go"button, the site will be reloaded.
    Is this necessary, when not: where can I disable this feature.
    John
  24. cssglobe on 14 Mar, 2008 wrote:

    Hi Ledzep,
    in the example I am using button type="submit". That submits the form. You can use button type="button" instead and the form will not be submitted.
  25. Thomas on 17 Mar, 2008 wrote:

    cssglobe,
    How do you link a search phase/term to a page? Meaning if I search for portfolio than press go how does it know to go to a page called portfolio?

    Thanks for your time
  26. eric on 25 Mar, 2008 wrote:

    can you make the suggestionbox go up instead of down?
  27. Alan Hogan on 9 Apr, 2008 wrote:

    Doesn't seem to do anything in Safari 3.
  28. ven on 17 Apr, 2008 wrote:

    Thanks for the great Stuff.
    I got a question… I have more then 1,000 suggestion Text, when I type "a" letter in textbox, its going down with huge right side browser scroll, can I control this with auto suggest display scroll (height may be 200px). Please help me on this issue.
  29. Richard on 17 Apr, 2008 wrote:

    Hi there, good work on this auto complete field. I was wondering if I can make a database connection inside the js file
    as I wanted to use it for retrieving live data?(coldfusion??)

    Thanks
  30. Gunter on 1 May, 2008 wrote:

    and now with german 'umlauts' please

    convert umlaute with entities
    example: ä - ä

    hope it helps
  31. gaby on 7 May, 2008 wrote:

    can it be set to search thru my database?
  32. Francisco on 13 May, 2008 wrote:

    hello, congratulations for you creation. But I think it has a bug in Internet Explorer, when you throw down some text in field-text and pressed the button 'intro/enter' error on page, " 'li [...]'" in your example in the 178 line .. Please tell me if you can correct it or how to do it, I use it on my page with this mistake but I can not. Thank you very much. Im using IE 7.. in firefox work fine!
  33. chester.. on 24 May, 2008 wrote:

    css textboxt input (textfield) style - examples - -
    http://www.css-lessons.ucoz.com/textbox-css-examples.htm
  34. Orides Tomkiel on 30 May, 2008 wrote:

    Nice work. Thanks so much!
  35. John on 31 May, 2008 wrote:

    Great tutorial, I submitted it to designbump.com, keep up the great work!
  36. sezer on 31 May, 2008 wrote:

    about css parameters
    http://css-lessons.ucoz.com/css-parameters.htm
  37. maggl on 5 Jun, 2008 wrote:

    nice work.

    how to sort the var suggestionText? anyone an answer?
  38. wwwcemil on 7 Jun, 2008 wrote:

    HI i need your help i really want to create my own website/web page but i dont know how to go about doing it so can you please help me out
  39. MarK on 10 Jun, 2008 wrote:

    Great job
    I'd like to know if it is possible to use it with a MySQL database to access data, and what i have to modifie to use it
    Thanks
  40. Pete on 12 Jun, 2008 wrote:

    I want to know how to link to a page from the terms that are in drop down when the user presses "go".

    I guess this is something to do with the Form Action. I have cgi/php.

    Can anyone please help as I would love to use this script.

    Many thanks
  41. asp-dersi on 12 Jun, 2008 wrote:

    HI i need your help i really want to
    create my own website/web page but i
    dont know how to go about doing it so
    can you please help me out
  42. Kyrill on 8 Jul, 2008 wrote:

    Hi,
    that great.
    But, how can I solve the problem, that I will load the "static list of suggestion options" from a text file or database?
  43. Phil on 7 Aug, 2008 wrote:

    This is quite cool.

    I am trying to use it for a text field that is loaded in an ajax call. In this case, the searchfield textbox hasn't been rendered when the script loads and runs.

    I am trying to call addEvent after the ajax call but it still isn't working.. Any ideas?
  44. Phil on 7 Aug, 2008 wrote:

    I figured it out, I don't need the event - I can just call the function "searchfield()" after loading
  45. Mario on 8 Aug, 2008 wrote:

    Nice work. Degrades perfectly in Safari for Windows, that's what I been looking for.
    I just wanted to add some interactivity with:
    if(field && safari){
    field.value = defaultText;
    field.onfocus = function(){ this.value = '' };
    field.onblur = function(){ this.value = defaultText };
    }
    Works, but I'm not a JS programmer, just tell me if that code is right.
    Thanks.
  46. Steve A. on 13 Oct, 2008 wrote:

    Nice but it seems to conflict with other CSS.
    I have it inside a div with a floated A and a SPAN and
    the div has an overflow: auto; to clear the float and that seems
    to make the generated ul invisible... Anyway I had to add heights to the A's so to remove the overflow property.

    Cheers
  47. sibel kuzgun on 16 Dec, 2008 wrote:

    How can I add more than one search field in a form?
  48. kyko on 22 Dec, 2008 wrote:

    Is this form working with pages meant to be browsed off-line from a CD? And where are the results shown after you press GO? Thanks!
  49. Evan on 30 Dec, 2008 wrote:

    This is excellent! Thank you so much.
  50. Gabriel on 28 Jan, 2009 wrote:

    I need to select the data to be displayed from a MySQL database. How can I do that? Any hint?
    Thanks in advance!
  51. Troy on 8 Mar, 2009 wrote:

    To limit the number of returns from the suggestionText variable place the following code in the "this.createList" function at the end of the for loop:

    if(i > "10") {break};

    That will limit it to 10 items in the list. Modify as necessary.
  52. Jérôme on 11 Mar, 2009 wrote:

    Hi,
    thanks it is really great.

    I was just wondering if it would be possible to add a parameter ton the searchfield JS function.
    I would like to have defaultText as a parameter instead of a local variable, just for localization.

    Any idea how to do it ?
  53. anthony on 31 Mar, 2009 wrote:

    Will this support multiple input box'es ? obiviously id's can't be the same...
  54. Rafael R.P on 28 Apr, 2009 wrote:

    Hello, How i can recive data from a MySql database?!?!?

    thx
  55. Rafael R.P on 28 Apr, 2009 wrote:

    I Have a solution, rename your searchform.js to .php
    on the top of document do the sql source for recive data,
    EX:
    <?
    header("Content-Type: text/html; charset=ISO-8859-1",true);

    mysql_connect("localhost", "root", "");
    mysql_select_db("database");
    $sql = mysql_query("select field from table order by field asc");
    while($x = mysql_fetch_assoc($sql)){
    $suggestPHP = $suggestPHP . $x['field'] . ', ';
    }
    ?>

    on var suggest on your js write var suggest = '<?=$suggestPHP?>
  56. Paul on 5 May, 2009 wrote:

    @ Rafael

    I tried using your code to get the data from a mysql database but it doesn't work.

    I get errors:

    PHP Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource

    and

    PHP Notice: Undefined variable: suggestPHP

    any ideas?
  57. Cynthia on 19 May, 2009 wrote:

    I add the code to my html page and it looks great but when I do a search it doesn't go anywhere. Am i missing something. I added both codes that he provided. Not sure. Thanks in advance!!
  58. beermohamed on 25 May, 2009 wrote:

    Please help me. how to add more than one search field in same window. This code not working in that page when we are adding more than one search field in same window.
  59. david on 15 Jun, 2009 wrote:

    HOWTO search not only from the beginning
    in the searchfield.js - if you replace the line:
    if(arrSrc[i].substring(0,value.length).toLowerCase() == value.toLowerCase()){

    with the line:
    if(arrSrc[i].indexOf(value.toLowerCase()) >= 0){

    the script also searches for the searchterm in the wordlist.

    for example:
    var suggestionText = 'google, android';

    if i type in "oo" it will now suggest me "google"

    hope i made my point clear

Sorry, further comments are disabled for this post.

CSS Globe is looking for writers!
Please contact me here!

Hey, you are not logged in!
Apply for a membership or login here.

Subscribe to CSSG Feed

Want to join?

If you wish to contribute with your own articles, updates or gallery entries you can apply for a membership and even become our editor.

Apply here

Become a friend