There is a neater way to handle the functionality you seek. I think what you want is a list of the images that have been clicked like @Shomz thinks as well. Is that correct?
1) The length property of the for loop is evaluated each iteration in the loop. Fetching the element from the DOM again with the index i
on each iteration is slow.
for(var i = 0; i < document.getElementsByClassName("face").length; i++){
document.getElementsByClassName("face")[i].addEventListener("click", counter)
}
An improvement is to change it into this:
var faces = document.getElementsByClassName("face");
for (var i = 0, var len = faces.length; i < len; i++) {
faces[i].addEventListener("click", counter)
}
2) But the code still attach an event listener to every single image. This is slow if you have many images. A better way is to let click events bubble upwards and catch them at a parent level. This is called event delegation. This way you don't need a loop, and merely a single event handler needs to be attached.
I store the id of the image, but you could store whatever you need from the node of course that is unique (the src?).
var clickedFaces = [];
document.getElementById('ImageContainer').addEventListener("click", onFaceClick);
function onFaceClick(e) {
if (e.target.className === 'face' && clickedFaces.indexOf(e.target.id) !== -1) {
clickedFaces.push(e.target.id);
}
}
If you want to know how many faces have been clicked:
console.log(clickedFaces.length);