Grow your CSS skills. Land your dream job.

Last updated on:

Clear Default Search String on Focus

$("#s")
    .val("Search...")
    .css("color", "#ccc")
    .focus(function(){
        $(this).css("color", "black");
        if ($(this).val() == "Search...") {
            $(this).val("");
        }
    })
    .blur(function(){
        $(this).css("color", "#ccc");
        if ($(this).val() == "") {
            $(this).val("Search...");
        }
    });
  1. Set value of field to "Search..."
  2. When field comes into focus, set color to black.
  3. If value is default, remove it.
  4. When field goes out of focus, set color back to light gray.
  5. If value is empty, put back default value

Comments

  1. Permalink to comment#

    I would like the text to only go back to grey if it is the default ‘search…’ text..

    blur(function(){
    if ($(this).val() == "") {
    $(this).css("color", "#ccc");
    $(this).val("Search...");
    }

  2. This is perfect and has made my day! Thanks.

  3. simona

    why it doesn’t work for me?
    this is my page
    please take a look, I’m going crazy

    http://www.athenarestauri.com/prova-jquery-2.html

    • Mike
      Permalink to comment#

      You need to put your jquery functions inside:

      $(document).ready(function(){
      // do jQuery stuff
      })

  4. Permalink to comment#

    @Dyllon

    $(“#searchfield”)
    .val(“Search…”)
    .css(“color”, “#999″)
    .focus(function(){
    $(this).css(“color”, “black”);
    if ($(this).val() == “Search…”) {
    $(this).val(“”);
    }
    })
    .blur(function(){
    $(this).css(“color”, “#999″);
    if ($(this).val() == “”) {
    $(this).val(“Search…”);
    }else if($(this).val() != “Search…”){
    $(this).css(“color”, “black”);
    }
    });

  5. Heo Chiên Bơ
    Permalink to comment#

    Hi, I’m new to jQuery!
    Sorry for my confusion as I know this can be done quite simple in javascript, just like this:

    --------------
     <form>
    ...
     <input id=string  onFocus="this.form.reset()">
    ...
     </form>
    --------------
    

    Is it much simpler?

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".