-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathjquery.placeholder.js
54 lines (44 loc) · 1.64 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
(function($) {
$.fn.placeholder = function(options) {
return this.each(function() {
var $this = $(this);
var placeholder = $this.attr('placeholder');
var clearOnFocus = (options && options['clearOnFocus']) || false;
// If we find a placeholder attribute on the element
if (placeholder) {
// Remove the placeholder attribute
$this.removeAttr('placeholder');
// Create and wrap the input in the input-holder
var inputHolder = $this.wrap($(document.createElement('span')).addClass('input-holder')).parent();
// Create the span that holds the default value
var inputDefault = $(document.createElement('span')).text(placeholder).addClass('input-default');
inputHolder.append(inputDefault);
// Pass clicks on the placeholder text through to the input
inputDefault.click(function() { $this.focus(); });
var updateDisplay = function() {
if ($this.val().length === 0) {
inputDefault.show();
} else {
inputDefault.hide();
}
};
// Hide placeholder if there is text in the input field
updateDisplay();
if (clearOnFocus) {
$this.focus(function(event) {
inputDefault.hide();
});
$this.blur(updateDisplay);
} else {
$this.keydown(function(event) {
if (event.keyCode !== '8' && event.keyCode !== '9' && event.keyCode !== '16') {
updateDisplay();
}
});
$this.keyup(updateDisplay);
}
$this.change(updateDisplay);
}
});
};
})(jQuery);