Toggle password visibility with JavaScript (Vanilla JavaScript)

Hey, in this example i am going to show you how to toggle password visibility with JavaScript. i.e how to hide and show password so that users can easily see what password they entered.

index.html

 
<div class="container">

    <h1>Javascript Password Visibility Toggle</h1>
    
    <div class="form">
    <div class="form-group">
        <input type="password" name="password" id="password" placeholder="Enter Password">
            <button type="button" id="togglePasssword">
                <i class="fa fa-eye-slash"></i>
            </button>
        </div>
    </div>
    
</div>
            

style.css


body,* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Open Sans', sans-serif;
}
.container {
    padding: 50px;
    text-align: center;
}
.form {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    height: 20vh;
    position: relative;
    flex-direction: column;
}
.form-group {
    position: relative;
    max-width: 400px;
    width: 100%;
}

/* Form Input */
input {
    width: 100%;
    border-radius: 10px;
    padding: 15px 20px;
    font-size: 18px;
    outline: none;
    color: #666;
    border: 1px solid #ddd;
    box-shadow: 0 4px 10px rgba(169, 169, 169, 0.2);
    transition: 0.2s linear;
}

input::placeholder {
    color: #aaa;
}
input:focus,
input:hover {
    box-shadow: 0 4px 20px rgba(169, 169, 169, 0.2);
}

/* Eye Button */
button {
    position: absolute;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    outline: none;
    cursor: pointer;
    font-size: 16px;
}
button i {
    color: #666;
    font-size: 16px;
}
            

script.js


let pwd = document.querySelector('#password');
let button = document.querySelector('#togglePasssword');

button.addEventListener('click', (e) => {
    if(pwd.type == 'password'){
        // If type is password
        e.target.setAttribute('class', 'fa fa-eye');
        pwd.type = 'text';
    } else {
        // If type is text
        e.target.setAttribute('class', 'fa fa-eye-slash');
        pwd.type = 'password';
    }
});
            

Output:

Password Visibilty - Hide:

Password Visibilty - Show:

To view the code on codepen - Check it out here


Post a Comment

0 Comments