Reputation: 383
I'm trying to hide all elements in a class (logos) except the element that is clicked on. So I wrote this out only to realize that it's impossible to pass arguments to functions activated by addEventListener! This seems... inflexible to say the least. Is there another obvious way to pass an argument that I'm blind to (I'm pretty new to Javascript)?
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<title>Sexism in Silicon Valley</title>
</head>
<body id="body1">
<div class="parent">
<img src="kstartup.png" class="logos" id="id1">
<img src="uber.png" class="logos" id="id2">
<img src="kpcb.png" class="logos" id="id3">
<img id="id4" src="r1startup.png" class="logos">
</div>
<div class="parent" id="parent2">
<img src="zillow.png" class="logos" id="id5">
<img src="github.png" class="logos" id="id6">
<img src="tinde.png" class="logos" id="id7">
<img src="snapchat.png" class="logos" id="id8">
</div>
<script src="index.js"></script>
</body>
</html>
Javascript:
function click(x) {
for (var i = 0; i < logos.length; i++) {
if (x !== i) {
logos[i].style.display = "hidden";
}
}
}
var logos = document.getElementsByClassName("logos");
for (var i = 0; i < logos.length; i++) {
logos[i].addEventListener('click', click(i));
}
Upvotes: 4
Views: 222
Reputation: 198314
The literal answer to your question:
logos[i].addEventListener('click', (function(i) { return function() { click(i); } })(i));
will do what you want. You need a function to wrap click(i)
, since you don't want to execute click(i)
immediately; and you need another function to close over i
, or you will get seemingly weird results (i.e. getting click(logos.length)
always).
What you want to do instead is not use the iterator at all. Attach a listener to #logos
itself; in the handler (which will get an event
parameter), iterate over its children and compare to event.target
.
Upvotes: 2