diff --git a/jquery.placeholder.js b/jquery.placeholder.js index 07bfc2b..6f32f15 100644 --- a/jquery.placeholder.js +++ b/jquery.placeholder.js @@ -17,6 +17,11 @@ var propHooks = $.propHooks; var hooks; var placeholder; + var events = { + 'clear': 'keydown.placeholder', + 'set' : 'keyup.placeholder blur.placeholder', + 'focus': 'focus.placeholder click.placeholder' + }; if (isInputSupported && isTextareaSupported) { @@ -39,12 +44,12 @@ $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.'+settings.customClass) - .bind({ - 'focus.placeholder': clearPlaceholder, - 'blur.placeholder': setPlaceholder - }) + .bind(events.clear, clearPlaceholder) + .bind(events.set, setPlaceholder) + .bind(events.focus, positionCaret) .data('placeholder-enabled', true) - .trigger('blur.placeholder'); + .each(setPlaceholder); + return $this; }; @@ -60,7 +65,7 @@ return $passwordInput[0].value; } - return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; + return $element.data('placeholder-enabled') && $element.hasClass(settings.customClass) ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); @@ -155,7 +160,8 @@ var input = this; var $input = $(input); var id = this.id; - if (input.value === '') { + + if (input.value === '' || (input.value == $input.attr('placeholder') && $input.hasClass(settings.customClass))) { if (input.type === 'password') { if (!$input.data('placeholder-textinput')) { try { @@ -169,7 +175,9 @@ 'placeholder-password': $input, 'placeholder-id': id }) - .bind('focus.placeholder', clearPlaceholder); + .bind(events.clear, clearPlaceholder) + .bind(events.focus, positionCaret); + $input .data({ 'placeholder-textinput': $replacement, @@ -182,11 +190,33 @@ } $input.addClass(settings.customClass); $input[0].value = $input.attr('placeholder'); + + // if the original input had focus, return focus + if ($input.is(':focus')) { + positionCaret.call($input[0]); + } } else { $input.removeClass(settings.customClass); } } + function positionCaret() { + var input = this, + $input = $(input); + + // if input is empty, position caret at the beginning + // otherwise let the browser select all input text + if (input.value == '' || (input.value == $input.attr('placeholder') && $input.hasClass(settings.customClass))) { + if (input.setSelectionRange) { + input.setSelectionRange(0, 0); + } else if (input.createTextRange) { + range = input.createTextRange(); + range.move('character', 0); + range.select(); + } + } + } + function safeActiveElement() { // Avoid IE9 `document.activeElement` of death // https://github.com/mathiasbynens/jquery-placeholder/pull/99