Reputation: 35
I have got this working as a multi-select that highlights each image on the first click, then unhighlights on the second click. However, sometimes the image will need to be clicked on twice to change, and sometimes only once. I can't figure out why!
Here is my code:
var ImageSelector = function() {
var imgs = null;
//var selImg = null;
var clicked = false;
var unClicked = true;
return {
addImages: function(container) {
imgs = container.getElementsByTagName("img");
for(var i = 0, len = imgs.length; i < len; i++) {
var img = imgs[i];
// img.className = "normal";
img.onclick = function() {
if(unClicked == true) {
this.className = "highlighted";
clicked = true;
unClicked = false;
}
else if(clicked == true) {
this.className = "normal";
clicked = false;
unClicked = true;
}
};
}
}
};
}();
var div = document.getElementById("Images");
ImageSelector.addImages(div);
Upvotes: 0
Views: 681
Reputation: 221
The clicked/unClicked variables are unnecessary here, because what you are essentially doing is toggling a class on each image.
Your code can be massively reduced to:
var ImageSelector = function() {
return {
addImages: function(container) {
container.onclick = function(e) {
var target = e.target;
if(target.nodeName === "IMG") {
target.className = (target.className === "highlighted") ? "normal" : "highlighted";
}
};
}
};
}();
var div = document.getElementById("Images");
ImageSelector.addImages(div);
img {
width: 100px;
height: 100px;
border: 1px black solid;
}
.highlighted {
background-color: red;
}
.normal {
}
<div id="Images">
<img />
<img />
</div>
Also, as a side note, if you know your variable is a Boolean before checking it in a conditional statement, you should use === or simply if(myVar)
or if(!myVar)
for checking truthy and falsy conditions, respectively.
I hope this helps.
Upvotes: 2