Are you really sure you or your users need this or is this meant as a convenience feature? No password field that I have seen allows to copy. Unless advertised, the number of people using this feature will be close to zero. Maybe a “copy password” link with ZeroClipboard is a better solution?
Anyway, here’s the best I could come up with. It uses jQuery-textrange plugin to handle text selection across browsers. It needs rather recent versions, too. jsfiddle demo.
The main idea is to make the low-opacity field ignore mouse events, so the user can select text in the password field normally. The advantage is that we don’t need to handle selection rendering at all. This can be achieved by CSS:
#account-password-hide { pointer-events: none; }
Next, once the user finishes a selection we get the selection position and select the same portion in the low-opacity field. Unfortunately, this will clear the selection in the password field.
$("#account_password").select(function () {
console.log("moving selection to hidden field");
var pos = $("#account_password").textrange();
$('#account-password-hide').textrange('set', pos.start, pos.end);
$('#account-password-hide').css("pointer-events", "auto");
});
CTRL+C works now, and so does right click → copy because we set pointer-events: auto
. If it were still none
, then a right click would go into the actual password field, preventing the copy operation.
Lastly we need to reset the pointer-events
so that the next click goes into the correct field again:
function reset() {
$('#account-password-hide').css("pointer-events", "none");
}
$('#account-password-hide').mousedown(function (evt) {
// allow right clicks
if (evt.which !== 3) {
reset();
}
});
$('#account-password-hide').mouseup(function () {
reset();
});
$('#account-password-hide').blur(function () {
reset();
});
As far as I can tell, this basically works.
In order to keep the selection on focus change, you’d have to create an additional element that holds the same characters as the password field (i.e. same look as the asteriks/dots in the password field). Then you can highlight the selected characters using CSS system colors. Getting z-index
and opacity
for each of them right is going to take some testing though.