Last active
January 3, 2016 06:29
-
-
Save lkacenja/8422674 to your computer and use it in GitHub Desktop.
Simple tiny jQuery plugin to handle form placeholding super easily.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
$.fn.placeholder = function(message) { | |
return this.each( | |
function() { | |
if ($(this).hasClass('form-placeholder-processed')) { | |
detach($(this)); | |
} | |
else { | |
$(this).addClass('form-placeholder-processed'); | |
$(this).data('form-placeholder', message); | |
$(this).data('form-placeholder-original-value', $(this).val()); | |
attach($(this), message); | |
} | |
} | |
); | |
} | |
function attach($el, message) { | |
if (!$.trim($el.val())) { | |
$el.val(message); | |
} | |
else { | |
$el.addClass('placeholder-active'); | |
} | |
$el.focus(handleFocus); | |
$el.blur(handleBlur); | |
var $form = $el.parents('form'); | |
if ($form && $form.length > 0) { | |
$form.submit(handleSubmit); | |
} | |
} | |
function detach($el) { | |
$el.unbind().removeClass('form-placeholder-processed'); | |
var originalValue = $el.data('form-placeholder-original-value'); | |
$el.val(originalValue); | |
var $form = $el.parents('form'); | |
if ($form && $form.length > 0) { | |
$form.unbind('submit'); | |
} | |
} | |
function handleFocus() { | |
$(this).addClass('placeholder-active'); | |
var message = $(this).data('form-placeholder'); | |
if ($(this).val() == message) { | |
$(this).val(''); | |
} | |
} | |
function handleBlur() { | |
if ($(this).val() == '') { | |
$(this).removeClass('placeholder-active'); | |
var message = $(this).data('form-placeholder'); | |
$(this).val(message); | |
} | |
} | |
function handleSubmit() { | |
$(this).find('.form-placeholder-processed').each( | |
function() { | |
var message = $(this).data('form-placeholder'); | |
if ($(this).val() == message) { | |
$(this).val(''); | |
} | |
} | |
); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment