/* * placeholder plugin for jquery * --- * copyright 2010, daniel stocks (http://webcloud.se) * released under the mit, bsd, and gpl licenses. */ (function($) { function placeholder(input) { this.input = input; if (input.attr('type') == 'password') { this.handlepassword(); } // prevent placeholder values from submitting $(input[0].form).submit(function() { if (input.hasclass('placeholder') && input[0].value == input.attr('placeholder')) { input[0].value = ''; } }); } placeholder.prototype = { show : function(loading) { // ff and ie saves values when you refresh the page. if the user refreshes the page with // the placeholders showing they will be the default values and the input fields won't be empty. if (this.input[0].value === '' || (loading && this.valueisplaceholder())) { if (this.ispassword) { try { this.input[0].setattribute('type', 'text'); } catch (e) { this.input.before(this.fakepassword.show()).hide(); } } this.input.addclass('placeholder'); this.input[0].value = this.input.attr('placeholder'); } }, hide : function() { if (this.valueisplaceholder() && this.input.hasclass('placeholder')) { this.input.removeclass('placeholder'); this.input[0].value = ''; if (this.ispassword) { try { this.input[0].setattribute('type', 'password'); } catch (e) { } // restore focus for opera and ie this.input.show(); this.input[0].focus(); } } }, valueisplaceholder : function() { return this.input[0].value == this.input.attr('placeholder'); }, handlepassword: function() { var input = this.input; input.attr('realtype', 'password'); this.ispassword = true; // ie < 9 doesn't allow changing the type of password inputs if ($.browser.msie && input[0].outerhtml) { var fakehtml = $(input[0].outerhtml.replace(/type=(['"])?password\1/gi, 'type=$1text$1')); this.fakepassword = fakehtml.val(input.attr('placeholder')).addclass('placeholder').focus(function() { input.trigger('focus'); $(this).hide(); }); $(input[0].form).submit(function() { fakehtml.remove(); input.show() }); } } }; var native_support = !!("placeholder" in document.createelement( "input" )); $.fn.placeholder = function() { return native_support ? this : this.each(function() { var input = $(this); var placeholder = new placeholder(input); placeholder.show(true); input.focus(function() { placeholder.hide(); }); input.blur(function() { placeholder.show(false); }); // on page refresh, ie doesn't re-populate user input // until the window.onload event is fired. if ($.browser.msie) { $(window).load(function() { if(input.val()) { input.removeclass("placeholder"); } placeholder.show(true); }); // what's even worse, the text cursor disappears // when tabbing between text inputs, here's a fix input.focus(function() { if(this.value == "") { var range = this.createtextrange(); range.collapse(true); range.movestart('character', 0); range.select(); } }); } }); } })(jquery); /*use it */ $(function(){ $('input[placeholder], textarea[placeholder]').placeholder(); });