Toggle Password Visibility using Javascript

This is the step by step procedure:

Step 1 : Add Dependency

In the header portion of your HTML, add the following:
  1. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  2. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

Step 2 : Add Style

Include the following style.
  1. <style type="text/css">
  2. #myInput{
  3. font-size: 1em;
  4. padding: 1em;
  5. }
  6. </style>

Step 3 : Create the Input

Next, we create our input type.
  1. <input type="password" id="myInput"> <button type="button" class="btn btn-primary" onclick="showPass()" id="showBtn"><i class="fa fa-eye" id="icon"></i> <span id="btnText">Show</span></button>

Step 4 : Adding our Script

Last step is to add our javascript code.
  1. function showPass() {
  2. var icon = document.getElementById('icon');
  3. var txt = document.getElementById('btnText');
  4. var btn = document.getElementById('showBtn');
  5. var x = document.getElementById('myInput');
  6. if (x.type === 'password') {
  7. x.type = 'text';
  8. btn.className = 'btn btn-default';
  9. txt.innerHTML = 'Hide';
  10. icon.className = 'fa fa-eye-slash';
  11. } else {
  12. x.type = 'password';
  13. btn.className = 'btn btn-primary';
  14. txt.innerHTML = 'Show';
  15. icon.className = 'fa fa-eye';
  16. }
  17. }

Full HTML

  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <title>Toggle Password Visibility using Javascript</title>
  4. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  5. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  6. <style type="text/css">
  7. #myInput{
  8. font-size: 1em;
  9. padding: 1em;
  10. }
  11. </style>
  12. </head>
  13. <div class="container">
  14. <h1 class="page-header text-center">Toggle Password Visibility using Javascript</h1>
  15. <div class="row">
  16. <div class="col-sm-4 col-sm-offset-4">
  17. <input type="password" id="myInput"> <button type="button" class="btn btn-primary" onclick="showPass()" id="showBtn"><i class="fa fa-eye" id="icon"></i> <span id="btnText">Show</span></button>
  18. </div>
  19. </div>
  20. </div>
  21. <script type="text/javascript">
  22. function showPass() {
  23. var icon = document.getElementById('icon');
  24. var txt = document.getElementById('btnText');
  25. var btn = document.getElementById('showBtn');
  26. var x = document.getElementById('myInput');
  27. if (x.type === 'password') {
  28. x.type = 'text';
  29. btn.className = 'btn btn-default';
  30. txt.innerHTML = 'Hide';
  31. icon.className = 'fa fa-eye-slash';
  32. } else {
  33. x.type = 'password';
  34. btn.className = 'btn btn-primary';
  35. txt.innerHTML = 'Show';
  36. icon.className = 'fa fa-eye';
  37. }
  38. }
  39. </body>
  40. </html>

Add new comment