placeholder fallback

by evpozdniakov

HTML

<form>
    <input name="username" placeholder="Username" />
    <input name="password" placeholder="Password" type="password" />
    <button type="submit">Login</button>
</form>

CSS

.placeholder-style {
    color: #999;
}

input {
    width: 120px;
}

JavaScript

$(function(){
    if ( !('placeholder' in document.createElement('input'))) {
        var changeTypeHelper = function(options){
            var re = new RegExp('type=\"?' + options.oldType + '\"?'),
                // two replace instead of one cause type=text is optional so it can be absent
                inputOuterHTML = options.$input[0].outerHTML.replace(re, '').replace(/>$/, 'type=' + options.newType + '>'),
                $inputClone = $(inputOuterHTML).insertAfter(options.$input);
            options.$input.remove();
            $inputClone.val(options.value).on('focus blur', placeholderHelper);
            if (options.focus) $inputClone.focus();
        }
        var placeholderHelper = function(evt){
            var $input = $(this);
            if (evt.type == 'focus') {
                if ($input.val() == $input.data('input-placeholder')) {
                    $input.removeClass('placeholder-style');
                    if ($input.data('input-type') == 'password' && 'outerHTML' in $input[0]) {
                        changeTypeHelper({
                            $input: $input,
                            oldType: 'text',
                            newType: 'password',
                            focus: true,
                            value: ''
                        })
                    } else {
                        $input.val('');
                    }
                }
            } else if (evt.type == 'blur' || evt.type == 'init') {
                if ($input.val() == '' && !$input.is(':focus')) {
                    $input.addClass('placeholder-style');
                    if ($input.data('input-type') == 'password' && 'outerHTML' in $input[0]) {
                        changeTypeHelper({
                            $input: $input,
                            oldType: 'password',
                            newType: 'text',
                            focus: false,
                            value: $input.data('input-placeholder')
  ...