Placeholder Polyfill

by Kyle Mitofsky

HTML

<input type="text" placeholder="Default 1" />
<input type="text" placeholder="Default 2" />
<input type="text" placeholder="Default 3" />
<input type="text" placeholder="Default 4" />
<input type="text" placeholder="Default 5" />
<input type="text" placeholder="Default 6" />















<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0;    
            background:lightgray;width:100%;'>
    About this SO Question: <a href='http://stackoverflow.com/q/24559797/1366033'>Apply Jquery .one function on elements with the same class</a><br/>         
<div>

CSS

input.placeholder {
    color: #1A89AD;
}

JavaScript

$.fn.selectRange = function(start, end) {
    if(!end) end = start; 
    return this.each(function() {
        if (this.setSelectionRange) {
            //this.focus();
            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();
        }
    });
};

placeholderPolyfill();

function placeholderPolyfill() {
    // added for purposes of debugging on modern browsers
    var alwaysUsePolyfill = true;

    if (alwaysUsePolyfill || !placeholderIsSupported()) {
        $("input[placeholder]").each(function() {

            $(this).val(this.placeholder)
                .addClass('placeholder')
                .on({
                    'mouseup keyup': function(e) {
                         // if we moused or tabbed in
                         if (e.type == "mouseup" || 
                             e.keyCode == 9) {
                             // pretend like their are no chars
                             $(this).selectRange(0);
                         }
                    },
                    'keydown': function(e) {
                         // check if we still have the placeholder
                         if (this.value == this.placeholder) {
                             $(this).val('')
                                    .removeClass('placeholder'); 
                         } 
                         // if tab key pressed - run keyup now
                         if (e.keyCode == 9) {
                             $(this).trigger('keyup');
                         }
                      },
                    'keyup': function(e) {
                          // if we're back to zero 
                          if (this.value.length === 0) {
                              // add placeholder back
                              ...