Web browsers provide security to password input via HTML input tag's type attribute, "password". It prevent against shoulder surfing attacks. But still if there is a requirement to view what is being typed in the password field the type's attribute need to change to "text" to view and change back after view.
Password Visibility Eye Bootstrap
This methods relies on
jQuery,
BootStrap and
Font awesome CDN libraries.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Bootstrap HTML Password Input with Eye</title>
<link rel="stylesheet" href="https://cdn.tutorialjinni.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.tutorialjinni.com/jquery/3.4.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.tutorialjinni.com/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.tutorialjinni.com/font-awesome/6.0.0-beta2/css/all.min.css" />
</head>
<body>
<div class="container">
<h4>Toggle Visibility With Eye Icon</h4>
<form class="form-inline">
<label class="sr-only" for="password">Password</label>
<div class="input-group mb-2 mr-sm-2">
<input type="password" class="form-control" id="password" placeholder="Password">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-eye-slash" id="eye"></i></div>
</div>
</div>
</form>
</div>
<script>
$(function(){
$('#eye').click(function(){
if($(this).hasClass('fa-eye-slash')){
$(this).removeClass('fa-eye-slash');
$(this).addClass('fa-eye');
$('#password').attr('type','text');
}else{
$(this).removeClass('fa-eye');
$(this).addClass('fa-eye-slash');
$('#password').attr('type','password');
}
});
});
</script>
</body>
</html>
Simple HTML Show Password
This method is depends uses vanilla JavaScript and simple HTML. For icon you need to be creative as there not close eye code for HTML. Here for this example we use HTML
Sun HTML code without rays for close eye and
Sun with rays html codes for open eye.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Simple HTML and Javascript Password View</title>
</head>
<body>
<form>
<input type="password" id="passowrdToggle" value="" placeholder="Password">
<input type="button" id="toggleButton" value="☉" />
</form>
<script>
const button = document.getElementById("toggleButton");
const passwordField = document.getElementById("passowrdToggle");
button.addEventListener("click", () => {
if (passwordField.getAttribute("type") === "password") {
passwordField.setAttribute("type", "text");
button.setAttribute("value", "☼");
} else {
passwordField.setAttribute("type", "password");
button.setAttribute("value", "☉");
}
});
</script>
</body>
</html>