How to get eye icon to toggle on/off password visibility?

Hi,

I’m using default spotlight theme and want to have an eye icon inside the password field to toggle on/off password visibility on login and signup page.

https://ausfin.in/account/login

https://ausfin.in/account/register

Hey @Abhishek_Singh

Follow these steps. They will help you a little.

1. Create HTML Login form with Eye Icon

We are going to place the eye icon inside the password text field. We can use the eye icon from the awesome font script library.

First of all import the awesome font Stylesheet into your HTML form page.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">

Use the tag <i> to display the eye icon. This icon is also known as the visibility eye icon.

<i class="far fa-eye" id="togglePassword"></i>

Use the below CSS to put the eye icon at the end of the password text field.

margin-left: -30px; 
cursor: pointer;

Put this tag below the passwords input field. This is how the sample form will look like with the password field.


2. Add JavaScript to Toggle Show/Hide Password

Copy and paste the below code into your JavaScript. This code is self-explanatory if you are familiar with the JavaScript basics.

const togglePassword = document.querySelector('#togglePassword');
  const password = document.querySelector('#id_password');

  togglePassword.addEventListener('click', function (e) {
    // toggle the type attribute
    const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
    password.setAttribute('type', type);
    // toggle the eye slash icon
    this.classList.toggle('fa-eye-slash');
});

Hey @Moeed ,

Sure it is working :blush: , but the password box is kind of overlapping. Idk why, but can u check it and tell how can I correct it? Just click on the password box and see.

https://ausfin.in/account/login

https://ausfin.in/account/register

@Moeed , Also it is working in a reverse manner, as when eye is off - it is showing password & when eye is on - it is not showing password.

Hey @Abhishek_Singh
It is working fine for me, as shown in the screenshot below.

Eye Open = Password will be hidden.

Eye Closed = Password will not be hidden

Hey @Moeed ,

All is good, but as you can see the field is kind of overlapping (dark black). I want it to cover the eye section as well. Can you tell me some way to correct it.

Thank you so much for helping me out this much.

I really appreciate it :blush:

It’s solved and I used below website to correctly do this stuff.

https://www.javascripttutorial.net/javascript-dom/javascript-toggle-password-visibility/