/** * jquery.placeholder http://matoilic.github.com/jquery.placeholder * * @version v0.2.4 * @author mato ilic * @copyright 2013 mato ilic * * dual licensed under the mit and gpl licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($, doc, debug) { var input = ('placeholder' in doc.createelement('input')), textarea = ('placeholder' in doc.createelement('textarea')), selector = ':input[placeholder]'; $.placeholder = {input: input, textarea: textarea}; //skip if there is native browser support for the placeholder attribute if(!debug && input && textarea) { $.fn.placeholder = function() {}; return; } if(!debug && input && !textarea) { selector = 'textarea[placeholder]'; } /* patch jquery.fn.val to return an empty value if the value matches * the placeholder */ $.fn.realval = $.fn.val; $.fn.val = function() { var $element = $(this), val, placeholder; if(arguments.length > 0) return $element.realval.apply(this, arguments); val = $element.realval(); placeholder = $element.attr('placeholder'); return ((val == placeholder) ? '' : val); }; function clearform() { $(this).find(selector).each(removeplaceholder); } function extractattributes(elem) { var attr = elem.attributes, copy = {}, skip = /^jquery\d+/; for(var i = 0; i < attr.length; i++) { if(attr[i].specified && !skip.test(attr[i].name)) { copy[attr[i].name] = attr[i].value; } } return copy; } function removeplaceholder() { var $target = $(this), $clone, $orig; if($target.is(':password')) return; if($target.data('password')) { $orig = $target.next().show().focus(); $('label[for=' + $target.attr('id') + ']').attr('for', $orig.attr('id')); $target.remove(); } else if($target.realval() == $target.attr('placeholder')) { $target.val(''); $target.removeclass('placeholder'); } } function setplaceholder() { var $target = $(this), $clone, plceholder, hasval, cid; placeholder = $target.attr('placeholder'); if($.trim($target.val()).length > 0) return; if($target.is(':password')) { cid = $target.attr('id') + '-clone'; $clone = $('') .attr($.extend(extractattributes(this), {type: 'text', value: placeholder, 'data-password': 1, id: cid})) .addclass('placeholder'); $target.before($clone).hide(); $('label[for=' + $target.attr('id') + ']').attr('for', cid); } else { $target.val(placeholder); $target.addclass('placeholder'); } } $.fn.placeholder = function() { this.filter(selector).each(setplaceholder); return this; }; $(function($) { var $doc = $(doc); $doc.on('submit', 'form', clearform); $doc.on('focus', selector, removeplaceholder); $doc.on('blur', selector, setplaceholder); $(selector).placeholder(); }); })(jquery, document, window.debug);