I’d like to change the following code to javascript only:
$(document).ready(function() {
$('.fa-eye, .fa-eye-slash').click(function() {
$(this).toggleClass('fa-eye fa-eye-slash');
var input=$(this).parent().find('input');
if(input.attr('type')=='password') {
input.attr('type', 'text');
}else input.attr('type', 'password');
});
});
What is does is when you click in an "eye icon" it changes that icon to "eye-slash icon" and changes the password field within the same div to text, so basically toggle password/text.
Since this is currently the only javascript I’m using, I thought it would be overkill to include jQuery or ZeptoJS only for this and this can probably be done with a few lines of javascript.
Please notice: this needs to be applied to multiple fields, that is why I opted not to use ID.
2
Answers
You can do it with normal vanilla JS means, see this snippet:
Note that jQuery is also Javascript, albeit, Javascript is not necessarily jQuery.
These are the corrections made to make it work with no jQuery and just relying on vanilla JS and Web API (https://developer.mozilla.org/en-US/):
.addEventListener()
to add bubbling event handlers to the elementsDOMContentLoaded
event instead of$(document).ready()
.querySelectorAll()
and.querySelector()
to select elements instead of using the$
function.classList.toggle()
instead of.toggleClass()
event.target
instead of$(this)
.getAttribute()
and.setAttribute()
instead ofattr()
.forEach()
to iterate over the array of returned elements