Show/hide password onClick of button using Javascript only

You are binding click event every time you click a button. You don’t want multiple event handlers. Plus you are redefining var pwShown = 0 on every click so you can never revert input state (pwShown stays the same).

Remove onclick attribute and bind click event with addEventListener:

function show() {
    var p = document.getElementById('pwd');
    p.setAttribute('type', 'text');
}

function hide() {
    var p = document.getElementById('pwd');
    p.setAttribute('type', 'password');
}

var pwShown = 0;

document.getElementById("eye").addEventListener("click", function () {
    if (pwShown == 0) {
        pwShown = 1;
        show();
    } else {
        pwShown = 0;
        hide();
    }
}, false);
<input type="password" placeholder="Password" id="pwd" class="masked" name="password" />
<button type="button" id="eye">
    <img src="https://cdn0.iconfinder.com/data/icons/feather/96/eye-16.png" alt="eye" />
</button>

Leave a Comment