-
Notifications
You must be signed in to change notification settings - Fork 0
/
jQuery.dPassword.js
355 lines (326 loc) · 12.6 KB
/
jQuery.dPassword.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*******************************************************************************
* dPassword v0.7 - delayed password masking (iPhone style)
* jQuery plugin
*
* Usage:
* e.g. <code>$('input[type=password]').dPassword(options)</code>
* The options parameter is optional and can have the following optional entries:
* delay: Number of seconds after which to hide input. Defaults to 1.
* observeForm: Whether to automatically deactivate when parent form is submitted (default: true).
* form: Form element different from parent form to observe for submitting (forces observeForm to true if set).
* cloakingCharacter: Character to replace entered characters with. Defaults to the bullet (•).
* onChange: Handler when password has been changed.
* onStateChange: Handler when masking behaviour changes.
* switchToPasswordType: Whether to switch input field back to password type on blur (looks bad in IE).
* showIcon: Show a lock icon allowing the user to toggle masking behaviour (defaults to true).
* See further options
* ICON_TITLE_ON, ICON_TITLE_OFF, ICON_PATH, ICON_STYLES, ICON_STYLES_ON, ICON_STYLES_OFF
* for customization.
*
* Licensed under MIT License.
*
* Copyright (c) 2009 Stefan Ullrich, DECAF° | http://decaf.de
* Dirk Schürjohann, DECAF° | http://decaf.de
* Julian Dreissig
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Known Issues: - view will not follow cursor if textfield is too small.
*
* @requires jQuery Library >= 1.3.2 (may work with older versions)
*/
(function() {
jQuery.fn.dPassword = function(options) {
// support multiple elements
if (this.length > 1) {
this.each(function() {jQuery(this).dPassword(options);});
return this;
}
var options = jQuery.extend(defaultOptions, options);
options.cloakingCharacter = options.cloakingCharacter.charAt(0);
var _input = jQuery(this);
var _value = null,
_previousInputValue = null,
_timeout = null,
_previousSelection = null,
_options = null,
_observing = false,
_form = null,
_toggleIcon = null,
_keysDown = {},
_inputFieldTypes = {};
// register event listeners
registerHandlers(_input);
if (options.observeForm || options.form) {
if (!_form) _form = options.form ? jQuery(options.form) : _input.closest('form');
if (_form) _form.bind("submit.dPassword", function(){deactivate(true);});
}
// create/handle toggle icon
if (options.showIcon) {
_toggleIcon = jQuery("<div class='dpassword-lock'></div>").insertAfter(_input);
_toggleIcon.css({backgroundImage: "url(" + (options.iconPath || options.ICON_PATH) + ")"});
_toggleIcon.css(options.ICON_STYLES);
_toggleIcon.bind("click", function() {
_observing ? deactivate() : activate();
_input.focus();
});
}
// TODO: public methods
// TODO: possible to overwrite val() to outside?
activate();
return this;
// ------- method declarations follow ----------
/**
* Returns the current value of the password field.
*/
function getValue() {
return _observing ? _value : _input.val();
}
/**
* Switches to active mode. Will be automatically called on initialization.
* Use getValue() to retrieve field value once activated.
*/
function activate() {
_observing = true;
_value = _input.val();
_cloakInput();
if (_toggleIcon) _switchToggleIcon(true);
if (options.onStateChange) options.onStateChange(_observing, this, _toggleIcon);
}
/**
* Deactivates dPassword temporarily/permanently and switches field back to normal password behaviour
* to e.g. perform DOM operations or value retrieval.
* IMPORTANT: If "temporarily" parameter is set to true will auto-reactivates on any input.
*/
function deactivate(temporarily) {
if (_observing) {
if (_timeout) {
clearTimeout(_timeout);
_timeout = null;
}
var selection = _getFieldSelection(_input);
jQuery.browser.msie ? _switchInputTypeIE("password") : _input.get(0).setAttribute("type", "password"); // override jQuery's behaviour
_input.val(getValue());
if (document.activeElement && document.activeElement == _input) _setFieldSelection(_input, selection);
if (temporarily !== true) {
_observing = false;
if (_toggleIcon) _switchToggleIcon(false);
if (options.onStateChange) options.onStateChange(_observing, this, _toggleIcon);
}
}
}
function _keyDownHandler(event) {
if (_observing) {
if (!(_isSpecialKey(event.keyCode) || event.metaKey || event.ctrlKey)) {
var keyCode = null;
for (var keyCode in _keysDown) {
_afterInputHandler(keyCode);
}
_storeSelection();
if (!keyCode) _cloakInput();
if (event.keyCode > 10) _keysDown[event.keyCode] = true;
} else {
_storeSelection();
if (_timeout) {
clearTimeout(_timeout);
_timeout = null;
_cloakInput();
}
}
}
}
function _keyUpHandler(event) {
if (_observing) {
if (event.type == "paste") {
setTimeout(_afterInputHandler, 0);
return;
}
if (_isSpecialKey(event.keyCode) || event.metaKey || event.ctrlKey) return;
if (_keysDown[event.keyCode] || event.keyCode < 11) _afterInputHandler(event);
} else {
var value = _input.val();
if (value != _previousInputValue) {
_previousInputValue = value;
if (options.onChange) options.onChange(getValue());
}
}
}
function _afterInputHandler(keyCode) {
delete _keysDown[keyCode];
var value = _input.val();
var selection = _getFieldSelection(_input);
if (_previousInputValue != value) {
var sStart = _previousSelection[0],
sEnd = _previousSelection[1],
sLength = _previousSelection[2],
lengthDifference = value.length - _value.length, // > 0: characters added
newValue;
if (lengthDifference < 0 && sLength == 0) { // single character deletion
if (sStart == selection[0]) { // forward deletion
newValue = _value.substring(0, sStart) + _value.substring(sEnd + 1);
} else { // has to be backward deletion
newValue = _value.substring(0, selection[0]) + _value.substring(sEnd);
}
} else { // a selection has been replaced/deleted
newValue = _value.substring(0, sStart) + value.substring(sStart, selection[1]) + _value.substring(sEnd);
}
_value = newValue;
if (options.onChange) options.onChange(getValue());
if (_timeout) {
clearTimeout(_timeout);
_timeout = null;
}
if (lengthDifference >= 0) {
// leave newly written part uncloaked
_cloakInput([sStart + 1, selection[1]]);
_timeout = setTimeout(_cloakInput, options.delay * 1000);
}
} else {
_previousSelection = selection;
}
}
function registerHandlers(element) {
element.bind("keydown.dPassword", _keyDownHandler);
element.bind("keyup.dPassword paste.dPassword", _keyUpHandler);
element.bind("select.dPassword focus.dPassword", _storeSelection);
if (options.switchToPasswordType) {
_input.bind("blur.dPassword", function() {deactivate(true);});
}
}
function _storeSelection() {
if (_observing) _previousSelection = _getFieldSelection(_input);
}
function _cloakInput(keepRange) {
var selection = _getFieldSelection(_input);
var value = _input.val();
if (keepRange) {
_input.val(value.substring(0, keepRange[0] - 1 ).replace(/./g, options.cloakingCharacter) + value.substring(keepRange[0] - 1, keepRange[1]) + value.substring(keepRange[1]).replace(/./g, options.cloakingCharacter));
} else {
_input.val(value.replace(/./g, options.cloakingCharacter));
if (_input.attr("type") != "text") {
if (jQuery.browser.msie) {
_switchInputTypeIE("text");
} else {
_input.get(0).setAttribute("type", "text"); // override jQuery's behaviour
}
_input.attr("autocomplete", "off");
}
}
if (document.activeElement && document.activeElement == _input.get(0)) _setFieldSelection(_input, selection);
_previousInputValue = _input.val();
}
function _switchInputTypeIE(toType) {
// create input field (or retrieve from cache) with new type
var newInput = _inputFieldTypes[toType];
if (!newInput) {
var tempDiv = _input.clone().wrap('<div></div>').parent();
if (toType == "password") {
tempDiv.html(tempDiv.html().replace(/>/, 'type="password">'));
} else {
tempDiv.html(tempDiv.html().replace(/type="?password"?/, 'type="text"'));
}
newInput = tempDiv.children();
registerHandlers(newInput);
}
// update field
newInput.css('width', (_input.get(0).clientWidth - 2*parseInt(_input.get(0).currentStyle.padding, 10)) + "px");
newInput.css('height', (_input.get(0).clientHeight - 2*parseInt(_input.get(0).currentStyle.padding, 10)) + "px"); // fix different widths for password and text inputs in IE
var oldInput = _input;
oldInput.get(0).replaceNode(newInput.get(0)); // jQuery's replaceWith method gobbles the event handlers, apparently.
_input = newInput;
_input.val(oldInput.val());
// first time here: store elements in cache
if (!_inputFieldTypes) {
_inputFieldTypes = {
password: (toType == "password") ? newInput : oldInput,
text: (toType == "password") ? oldInput : newInput
};
}
}
function _switchToggleIcon(state) {
if (state) {
_toggleIcon.css(options.ICON_STYLES_OFF).css({className: "dpassword-lock-closed"});
_toggleIcon.attr('title', options.ICON_TITLE_ON);
} else {
_toggleIcon.css(options.ICON_STYLES_ON).css({className: "dpassword-lock-closed"});
_toggleIcon.attr('title', options.ICON_TITLE_OFF);
}
}
};
var defaultOptions = {
delay: 1,
observeForm: true,
form: null,
cloakingCharacter: (navigator.platform == "MacIntel") ? '\u2022' : '\u25CF',
onChange: null,
onStateChange: null,
showIcon: false,
switchToPasswordType: !jQuery.browser.msie,
/*
* Default styles and behaviours for lock icon, see showIcon option.
* Override at will.
*/
ICON_TITLE_ON: "Delayed masking active, click here to switch off.",
ICON_TITLE_OFF: "Click to activate delayed masking of input.",
ICON_STYLES: {
display: "inline",
position: "absolute",
width: "16px", height: "16px",
margin: "-10px 0 0 -12px",
overflow: "hidden", cursor: "pointer",
backgroundRepeat: "no-repeat"
},
ICON_PATH: "lock.gif", // set to your position of icon
ICON_STYLES_OFF: {
backgroundPosition: "0 0"
},
ICON_STYLES_ON: {
backgroundPosition: "0 -16px"
}
};
function _getFieldSelection(element) {
if (document.selection) {
var range = document.selection.createRange();
var length = range.text.length;
range.moveStart('character', -element.val().length); // Move selection start to 0 position
var cursorPos = range.text.length; // The caret position is now the selection length
return [cursorPos - length, cursorPos, length];
} else {
var el = element.get(0);
return [el.selectionStart, el.selectionEnd, el.selectionEnd - el.selectionStart];
}
}
function _setFieldSelection(element, selection) {
var el = element.get(0);
if (document.selection) {
var range = el.createTextRange();
range.collapse();
range.moveStart('character', selection[0]);
range.moveEnd('character', selection[1] - selection[0]);
range.select();
} else {
el.selectionStart = selection[0];
el.selectionEnd = selection[1];
}
}
function _isSpecialKey(keyCode) {
// TODO: Need to check OS? Windows key?
return (keyCode >= 9 && keyCode <= 20) || (keyCode >= 33 && keyCode <= 40) || keyCode == 224;
}
})();