Search code examples
javascripthtmlcssplaceholdertextinput

How to create a label inside an <input> element and style it?


I can make my label inside an input element (my "disappearing text"):

HTML

<input name="firstName" type="text" maxlength="40" value="Enter your first name"
 onfocus="if(this.value==this.defaultValue)this.value=''" 
 onblur="if(this.value=='')this.value=this.defaultValue" />

Then style it so my disappearing text is faded (#333). And style it so when I start to input a value into the field the text is black (#000).

CSS

input[type=text] {
    color: #333;
}
input[type=text]:focus {
    color: #000;
}

It all works fine until you move onto the next input field. Then the field you just entered a value in changes back to the #333 color. I can see why that happens, but can't quite get to how to keep the value black #000 color if the input field has had a value put into it.

Thanks in advance for the assist and education!


Solution

  • This appears to work xbrowser using a combination of jQuery and the Modernizer library.

    Requires the jQuery and Modernizer Libraries be on the site and properly referenced.

    HTML

    <head>
    <script src="jquery-1.9.1.min.js"></script>
    <script src="modernizr.js"></script>
    
    <script>
    $(document).ready(function(){
    
    if(!Modernizr.input.placeholder){
    
    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });
    
    }
    </script>
    </head>
    
    <body>
    <form>
    <input name="firstName" type="text" maxlength="40" placeholder="Enter your first name">
    </form>
    

    CSS

    input[type=text] {
    color: #000;
    }
    
    input[type=text].placeholder {
    color: #666;
    }
    

    SOURCE: http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text