AnApprentice
AnApprentice

Reputation: 110950

jQuery placeholder that shows the placeholder until text is typed

notice how the placeholder works on the Stackoverflow ask a question title and on Twitter's Sign Up form: https://twitter.com/signup

The placeholder has two states:

  1. No selected (placeholder shown)
  2. Selected, but 0 input (placeholder shown, lighter color)

Does anyone know of a jQuery plugin that supports this? I've seen jQuery placeholder plugins that support #1, but not #2.

Thanks

Upvotes: 3

Views: 3953

Answers (3)

Jonathan Tonge
Jonathan Tonge

Reputation: 1518

I wrote this for my own projects and it works great (requires jQuery) and super easy to implement. It actually works better than native placeholder support and just like the Twitter signup.

Features:

  • placeholder is grey text and turns to lightgrey when in focus.
  • placeholder is available whenever there is nothing typed in the input field (shows itself when you delete)
  • if you click anywhere within the placeholder, the text cursor goes to the start of the field, meaning that you can't highlight it, or type in the middle of it for instance
  • works flawlessly moving back and forth the inputs both with tab and mouse and on input reuse
  • easy-to-use on just one or all input fields ( .placeHolder(); )
  • <1kb

1.Copy this script to a text file, save as placeholder.js and upload to your js directory:

    (function( $ ){

       $.fn.placeHolder = function() {  
          var input = this;
          var text = input.attr('placeholder');  // make sure you have your placeholder attributes completed for each input field
          if (text) {
              input.val(text).css({ color:'grey' });
              input.focus(function(){  
                  if (input.val() === text) input.animate({ color:'lightGrey' }, 350).selectRange(0,0).one('keydown', function(){     
                      input.val("").css({ color:'black' });  
                  });
              });
              input.blur(function(){ 
                  if (input.val() == "" || input.val() === text) input.val(text).css({ color:'grey' }); 
              }); 
              input.keyup(function(){ 
                  if (input.val() == "") input.val(text).css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
                      input.val("").css({ color:'black' });
                  });     
              });   
              input.mouseup(function(){
                   if (input.val() === text) input.selectRange(0,0); 
              }); 
           }
       };

       $.fn.selectRange = function(start, end) {
            return this.each(function() {
                if (this.setSelectionRange) { this.setSelectionRange(start, end);
                } else if (this.createTextRange) {
                     var range = this.createTextRange();
                     range.collapse(true); 
                     range.moveEnd('character', end); 
                     range.moveStart('character', start); 
                     range.select(); 
                }
            });
       };

    })( jQuery );

To use on just one input

$('#myinput').placeHolder();  // just one

<script type="text/javascript" src="../js/placeholder.js"></script>   //include this in your header unless you are going to implement the placeholders for just non-HTML5 browsers. In that case see below. 

To use on all input fields

$(":input").each(function(){   // this will work for all input fields
    $(this).placeHolder();
});

<script type="text/javascript" src="../js/placeholder.js"></script>  // include in header / change src to your actual js directory

This is how I recommend you implement it on all input fields on your site only when the browser does not support HTML5 placeholder attributes:

var placeholder = 'placeholder' in document.createElement('input');  
if (!placeholder) {      // if the browser does not support placeholder, then use this script
  $.getScript("../js/placeholder.js", function() {   // save the above script as placeholder.js
      $(":input").each(function(){   // this will work for all input fields
        $(this).placeHolder();
      });
  });
} 

Remember to remove the placeholder values when you submit:

$('#submit').click(function(){
   var text = this.attr('placeholder');
   var inputvalue = this.val();  // you need to collect this anyways
   if (text === inputvalue) inputvalue = "";

  // $.ajax(...  // do your ajax thing here

});

Upvotes: 1

MrColes
MrColes

Reputation: 2493

You can try the persistent placeholders approach (jsfiddle included). It makes a label tag work just like a placeholder in order to get what you’re asking for, i.e., the text still appears, but lighter when there’s focus but no input.

Here’s an example of the markup:

<div class="input-wrapper">
    <label for="id_username">Username</label>
    <input id="id_username" type="text" name="username">
</div>

There’s some additional JS and CSS to make it do what you want. It’s very similar to how twitter and tumblr do it. Some nice side-effects of this approach are:

  • you never have to worry about placeholder text messing up data in your forms
  • the placeholders will work in password fields
  • accessible markup

Upvotes: 1

jyore
jyore

Reputation: 4825

Here is a quick and easy example to get you started.

HTML

<input type='text' id='in' value='Enter Something...'>

JavaScript

$('#in').bind({
    click : function() {
        $(this).css('color','#ccc');
    },
    focusout : function() {
        $(this).css('color','#000');
    },
    keydown : function() {
        $(this).val('');
        $(this).css('color','#000');
        $(this).unbind('keydown');
        $(this).unbind('click');
    },
});

Good luck

EDIT: I increased the functionality and packaged it as a plugin, you can get it at Github, the jQuery Plugin Site or from the Project Home (Demo & Documentation Available)

Upvotes: 7

Related Questions