Treehouse: 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. Dyllon
    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. StuartH
    Permalink to comment#

    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. Matt
    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

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```