posted on:January 7, 2008

Style Your Websites Search Field with JSCSS


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.

Enjoyed the article?

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

DeliciousStumbleUpon RedditSubscribe

Comments (59 Comments)

  1. dodot
    January 9, 2008

    Nice work Alen!
  2. SMASHINGAPPS.COM
    January 9, 2008

    Great job.
  3. Colin
    January 9, 2008

    >> 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
    January 9, 2008

    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
    January 10, 2008

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

    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
    January 10, 2008

    or you could commented that line :)
  8. cssglobe
    January 10, 2008

    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
    January 16, 2008

    This is nice work. Thanks
  10. hcabbos
    January 18, 2008

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

    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
    January 19, 2008

    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
    January 26, 2008

    Nice work... and now with german 'umlauts' please :-)
  14. Dragon
    January 27, 2008

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

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

    Thanks for the great information.......this should help in my web design
  17. meyabilisim
    January 30, 2008

    Nice work. Thanks so much!
  18. Thomas
    February 21, 2008

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

    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
    February 27, 2008

    enter is nothing error line 179 for(var i=0;i<li.length;i++){ :(
  21. Thomas
    March 3, 2008

    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
    March 3, 2008

    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
    March 14, 2008

    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
    March 14, 2008

    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
    March 17, 2008

    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
    March 25, 2008

    can you make the suggestionbox go up instead of down?
  27. Alan Hogan
    April 9, 2008

    Doesn't seem to do anything in Safari 3.
  28. ven
    April 17, 2008

    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
    April 17, 2008

    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
    May 1, 2008

    and now with german 'umlauts' please convert umlaute with entities example: ä - ä hope it helps
  31. gaby
    May 7, 2008

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

    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..
    May 24, 2008

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

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

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

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

    nice work. how to sort the var suggestionText? anyone an answer?
  38. wwwcemil
    June 7, 2008

    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
    June 10, 2008

    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
    June 12, 2008

    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
    June 12, 2008

    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
    July 8, 2008

    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
    August 7, 2008

    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
    August 7, 2008

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

    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.
    October 13, 2008

    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
    December 16, 2008

    How can I add more than one search field in a form?
  48. kyko
    December 22, 2008

    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
    December 30, 2008

    This is excellent! Thank you so much.
  50. Gabriel
    January 28, 2009

    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
    March 8, 2009

    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
    March 11, 2009

    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
    March 31, 2009

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

    Hello, How i can recive data from a MySql database?!?!? thx
  55. Rafael R.P
    April 28, 2009

    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
    May 5, 2009

    @ 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
    May 19, 2009

    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
    May 25, 2009

    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
    June 15, 2009

    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, the comment form is closed at this time.