-
Notifications
You must be signed in to change notification settings - Fork 111
/
jquery.placeholder.js
73 lines (72 loc) · 2.72 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
/*
* Placeholder plugin for jQuery
* @author Daniel Stocks (http://webcloud.se)
* @version 0.1
*/
(function($) {
function Placeholder(input) {
// Special treatment for password inputs
if (input.attr('type') == 'password') {
input.attr('realType', 'password');
this.isPassword = true;
}
this.input = input;
// IE doesn't allow changing the type of password inputs
this.fakePassword = $("<input>").val(input.attr('placeholder')).focus(function() {
input.trigger("focus")
$(this).hide();
});
}
Placeholder.prototype = {
show : function(loading) {
// FF and IE saves values when you refresh the page. If the user refreshes the page with
// the placeholders showing they will be the default values and the input fields won't be empty.
if (this.input[0].value == '' || (loading && this.valueIsPlaceholder())) {
if (this.isPassword) {
try { // IE doesn't allow us to change the input type
this.input[0].setAttribute('type', 'text');
} catch (e) {
this.input.before(this.fakePassword.show()).hide();
}
}
this.input[0].value = this.input.attr('placeholder');
this.input.addClass('placeholder');
}
},
hide : function() {
if (this.valueIsPlaceholder() && this.input.hasClass('placeholder')) {
if (this.isPassword) {
try {
this.input[0].setAttribute('type', 'password');
} catch (e) { }
// Restore focus for Opera and IE
this.input.show()
this.input[0].focus();
}
this.input[0].value = '';
this.input.removeClass('placeholder');
}
},
valueIsPlaceholder : function() {
return this.input[0].value == this.input.attr('placeholder');
}
}
var supported = !!("placeholder" in document.createElement( "input" ));
$.fn.extend({
placeholder: function() {
return this.each(function() {
if(!supported) {
var input = $(this);
var placeholder = new Placeholder(input);
placeholder.show(true);
input.focus(function() {
placeholder.hide();
});
input.blur(function() {
placeholder.show(false);
});
}
});
}
});
})(jQuery);