I want to create password toggle function when clicked on the eye icon using Javascript only. I have written code for it but it works only to show the password text and not
This is an improvement upon Tunaki's answer. We don't even care to check which state the form field is in already, because this will be entirely determined by the state of the mouse. This allows the password to be only momentarily viewed (only as long as the mouse button is held down over the button.)
<html>
<head>
<title>Visible Password Test</title>
</head>
<body>
Password : <input type="password" name="password" id="password" />
<button type="button" id="eye" title="Did you enter your password correctly?"
onmousedown="password.type='text';"
onmouseup="password.type='password';"
onmouseout="password.type='password';">Peek at Password</button>
</body>
</html>
In your code everytime when you call showHide() function, pwShown variable is set to 0.
You need to declare pwShown variable as global one.
var pwShown = 0;
function showHide()
{
...
}
We can get by using onclick event, let's see example.It is very easy
HTML
<span>
<img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" onclick="showHide()" id="eye" />
</span>
Javascript
function showHide() {
if (pwd.type == 'text') {
pwd.type = 'password';
}
else {
pwd.type = 'text';
}
}
JQuery solution from my code: (just change the IDs).
$(document).ready(function () {
$("#eye").click(function () {
if ($("#password").attr("type") === "password") {
$("#password").attr("type", "text");
} else {
$("#password").attr("type", "password");
}
});
});
function action() {
var my_pass = document.getElementById("pass");
if (my_pass.type === "password") {
my_pass.type = "text";
} else {
my_pass.type = "password";
}
}
<input type="checkbox" onclick="action()">Show <input type="password" id="pass" value="my-secret">
Based on what you wrote, you are adding the event both in html and in javascript (inside showHide
function). May be you can change your js code from what you have, to:
function showHide()
{
var input = document.getElementById("pwd");
if (input.getAttribute("type") === "password") {
show();
} else {
hide();
}
}