So I thought I would build an ‘out-of-the-box’ solution using App Connect framework and Bootstrap 5.
Note: it only works with BS5.
Anyway here you have an App Connect custom extension to toggle the password visibility.
Add the following code to a js file and then import it in the page you want to use it in.
<script src="/js/custom/dmx-jonl-passvis.js" defer=""></script>
Custom code:
dmx.Attribute('jonl-passvis', 'mounted', function (node, attr) {
let span = document.createElement('span')
span.setAttribute('class', 'input-group-text')
switch (attr.argument) {
case 'icon':
span.innerHTML = '<span id="togglePassword" class="' + attr.value.split('::')[0] + '" id="togglePassword" style="cursor: pointer"></span>';
span.addEventListener('click', function () {
node.setAttribute('type', node.type == 'password' ? 'text' : 'password')
document.getElementById('togglePassword').setAttribute('class', node.type == 'password' ? attr.value.split('::')[0] : attr.value.split('::')[1])
})
break;
case 'text':
span.innerHTML = '<span id="togglePassword" style="cursor: pointer">' + attr.value.split('::')[0] + '</span>';
span.addEventListener('click', function () {
node.setAttribute('type', node.type == 'password' ? 'text' : 'password')
document.getElementById('togglePassword').innerText = node.type == 'password' ? attr.value.split('::')[0] : attr.value.split('::')[1]
})
break;
default:
// do nothing
}
node.insertAdjacentElement('afterend', span)
});
How do you use it?
Just add a new attribute to your password input called dmx-jonl-passvis
.
The attribute takes an argument that can be icon
or text
and as value it will take two values separated by ::
.
If you choose to display an icon the first value will be the icon for the show action and the second will be for the hide action.
If you choose to display text the first value will be the string to show and the second one the string to hide.
When you click on the icon or the text it will toggle the visibility.
Icon example
<input class="form-control" type="password" name="new-password" id="new-password" autocomplete="new-password" dmx-jonl-passvis:icon="far fa-eye::far fa-eye-slash">
Text example
<input class="form-control" type="password" name="new-password" id="new-password" autocomplete="new-password" dmx-jonl-passvis:text="Show::Hide">