forked from mathiasbynens/jquery-placeholder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.placeholder.js
89 lines (82 loc) · 2.51 KB
/
jquery.placeholder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*!
* HTML5 Placeholder jQuery Plugin v1.7
* @link http://github.com/mathiasbynens/Placeholder-jQuery-Plugin
* @author Mathias Bynens <http://mathiasbynens.be/>
*/
;(function($) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea');
if (isInputSupported && isTextareaSupported) {
$.fn.placeholder = function() {
return this;
};
} else {
$.fn.placeholder = function() {
return this.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.bind('focus.placeholder', clearPlaceholder)
.bind('blur.placeholder', setPlaceholder)
.trigger('blur.placeholder').end();
};
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (!rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder() {
var $input = $(this);
if ($input.val() === $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input.hide().next().show().focus();
} else {
$input.val('').removeClass('placeholder');
}
}
}
function setPlaceholder(elem) {
var $replacement,
$input = $(this);
if ($input.val() === '' || $input.val() === $input.attr('placeholder')) {
if ($input.is(':password')) {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ type: 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args($input[0]), { type: 'text' }));
}
$replacement
.removeAttr('name')
.data('placeholder-password', true)
.bind('focus.placeholder', clearPlaceholder);
$input
.data('placeholder-textinput', $replacement)
.before($replacement);
}
$input = $input.hide().prev().show();
}
$input.addClass('placeholder').val($input.attr('placeholder'));
} else {
$input.removeClass('placeholder');
}
}
$(function() {
// Look for forms
$('form').bind('submit.placeholder', function() {
// Clear the placeholder values so they don’t get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('unload.placeholder', function() {
$('.placeholder').val('');
});
})(jQuery);