$.fn.watermark = function () { // if no support for placeholder attribute the apply jquery if (!Modernizr.input.placeholder) { // run the loop for each selected element $(this).each(function () { // set placeholder values, in input field is empty if ($(this).val() === '') // if field is empty { $(this).val( $(this).attr('placeholder') ); } // focus and blur of placeholders $(this).focus(function() { // if the value of the input and the value of the placeholder attr is same then // empty the input control, and remove the placeholder class. if ($(this).val() === $(this).attr('placeholder')) { $(this).val(''); $(this).removeClass('placeholder'); // ready for typing in. } }).blur(function() { // if the input value is empty or same as placeholder value if ($(this).val() === '' || $(this).val() === $(this).attr('placeholder')) { // set the inpu tvalue as placeholder attribute value and add the // placeholder class to the input. $(this).val($(this).attr('placeholder')); $(this).addClass('placeholder'); } }); // remove placeholders on submit $('[placeholder]').closest('form').submit(function() { $(this).find('[placeholder]').each(function() { if ($(this).val() == $(this).attr('placeholder')) { $(this).val(''); } }); }); return this; // for chaining }); return this; // chaining } }; $(".placeholder").watermark();
<div id="result"></div> <form class="form"> <ul> <li> <label>Name</label> <input class="placeholder" placeholder="Enter your full name." type="text" /> </li> <li> <label>Email</label> <input class="placeholder" placeholder="Enter your email address." type="text" /> </li> <li> <label>Message</label> <textarea class="placeholder" placeholder="Let us know what you think."></textarea> </li> <li> <input value="Submit" type="submit" /> </li> </ul> </form>
article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } .placeholder { color: lightgray; } .form ul { list-style: none; } .form label { display: block; font-weight: bold; } .form input[type=text] { width: 500px; } .form textarea { width: 500px; height: 100px; }