Magento password view and hide function using js

This post is about how to add a image in the password text area to show and hide password ,

this can be done with the help of a javascript and a code inside the text field

Here i’m attaching a code of password with a eye icon click to view and hide

                <div class="field password required">
                    <label for="pass" class="label" ><span><?= $block->escapeHtml(__('Password')) ?></span></label>
                    <div class="control">
                        <div class="icons-sign"><img class="iconbutton-img" src="<?php echo $this->getViewFileUrl("images/privacy.png") ?>"></div>
                        <input name="login[password]" type="password" placeholder="Password" id="password"
                            <?php if ($block->isAutocompleteDisabled()): ?> autocomplete="off"<?php endif; ?>
                               class="input-text pass-view" id="pass"
                               title="<?= $block->escapeHtmlAttr(__('Password')) ?>"
                               data-validate="{required:true}">
                        <div class="icons eye">
                            <img class="iconbutton-img-eye" id="togglePassword" src="<?php echo $this->getViewFileUrl("images/bisibility.png") ?>"></div>
                    </div>
                </div>

Now script for the following code is given below:

const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#password');
togglePassword.addEventListener('click', function (e) {
    // toggle the type attribute
    const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
    password.setAttribute('type', type);
    this.classList.toggle('pass-view');
});

Please go through the code and script in case to change the classes as per your need

Leave a comment

Your email address will not be published. Required fields are marked *