Considering a password input field I want to show the last character of input for milliseconds and then change back to normal password input like this:
var showLength = 1;
var delay = 1000;
var hideAll = setTimeout(function() {}, 0);
$(document).ready(function() {
$("#password").on("input", function() {
var offset = $("#password").val().length - $("#hidden").val().length;
if (offset > 0) $("#hidden").val($("#hidden").val() + $("#password").val().substring($("#hidden").val().length, $("#hidden").val().length + offset));
else if (offset < 0) $("#hidden").val($("#hidden").val().substring(0, $("#hidden").val().length + offset));
// Change the visible string
if ($(this).val().length > showLength) $(this).val($(this).val().substring(0, $(this).val().length - showLength).replace(/./g, "•") + $(this).val().substring($(this).val().length - showLength, $(this).val().length));
// Set the timer
clearTimeout(hideAll);
hideAll = setTimeout(function() {
$("#password").val($("#password").val().replace(/./g, "•"));
}, delay);
});
});
#hidden {
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password" type="text" value="" />
<input id="hidden" type="text" value="" />
The above code works fine except one annoying issue:
If you type 123456789
and try to remove the first or second or any of the characters inside the input field you would see that it only removes the last character of hidden input (which is the input field we want to send its data to the server)
Seems that we should somehow detect the position of the type cursor (which may be moved by mouse or arrow keys on the keyboard) and remove that specific character...
How can we fix this issue?
Note: I searched Stack Overflow, and none of the codes or jQuery plugins can do this properly. I would like a once-for-all solution for this.