I have made a password reveal feature, however the code is duplicated. Essentially all I want to be able to improve the code, however I'm not exactly sure how I could do this, all I know is it would consist of some form of loop.

I would go straight to jQuery but there is no need in 2018.

This is my functionality markup for my HTML (it’s the same for the login page and modal):

<form action="/login" method="post">

<div class="input-group">
</div>

<div class="input-group">
</div>

<div class="input-group--flex">
<div class="remember-me">
<input type="checkbox"/> Remember Me
</div>

</div>
</div>

<div class="input-group">
</div>
</form>


And this is my JavaScript, which shows both the login page and login modal code to demonstrate what I have so far:

document.addEventListener("DOMContentLoaded", function(event) {

} else {
}
});
}

} else {
}
});
}
});


FYI I'm fairly new to the world of JavaScript so I'm not very good.

Before I comment on your implementation. Your code has a bug in it.

The code inside this if block:

if(modalShowPassword || modalPassword) {


will execute if either modalShowPassword or modalPassword is set but you really only want it to execute if both are set. You want to use the and (&&) operator like this:

if(modalShowPassword && modalPassword) {


With your code, think about what would happen if you were to have more (say 10) password boxes on your page? Would you repeat your code 10 times with different variables and different values for the data-js attribute? What I would suggest is to use something similar to the Bootstrap style (see how their modal dialogs work here https://getbootstrap.com/docs/4.1/components/modal/#via-data-attributes). There are two things to note. First they use the same data attribute for all instances even if there are multiple modals on the page. Secondly they do not apply an attribute to the modal form. They have two attributes on the toggle button, data-toggle defines the action while data-target tells the button what to show as a modal.

So a solution might look like:

<form>

</form>

<script>
var targetSelector = item.getAttribute('data-target');
if (!targetSelector)
return;
var target = document.querySelector(targetSelector);
if (!target)
return;


• Yes, I agree it is confusing. Basically an array has a really handy forEach method so you could normally call someArray.forEach(...). However querySelectorAll returns a NodeList which doesn't have that method. Basically what that code does is take the forEach method from an array and call it with the list of nodes returned by querySelectorAll. – Marc Rohloff Aug 28 '18 at 16:06
• Side note, I've seen examples that just use passwordReveals.forEach so maybe that's not 100% correct. You could test it that way. – Marc Rohloff Aug 28 '18 at 16:07