When I click on the link for "id2", it executes the filter function for every link, ending with "id5" as the visible filtered list on my page.
<script>
window.onload = function() {
var a = document.getElementById("id1");
var b = document.getElementById("id2");
var c = document.getElementById("id3");
var d = document.getElementById("id4");
var e = document.getElementById("id5");
var x = document.getElementsByClassName("className")
a.onclick = filter(a.id);
b.onclick = filter(b.id);
c.onclick = filter(c.id);
d.onclick = filter(d.id);
e.onclick = filter(e.id);
function filter(tag) {
for (var i = 0; i < x.length; i++)
if (tag === "view all") {
x[i].style.display = "block";
}
else {
if (tag.toLowerCase() === x[i].getAttribute('alt').toLowerCase())
x[i].style.display = "block";
else
x[i].style.display = "none";
}
return false;
}
}
The top part where I have set up my links appears as follows:
<a href="" id="id1" rel="history" class="active">View All</a>
<a href="" id="id2" class="active">ID 2</a>
<a href="" id="id3" class="active">ID 3</a>
<a href="" id="id4" class="active">ID 4</a>
<a href="" id="id5" class="active">ID 5</a>
The filter works correctly, the only issue is that it is executing the function for all links!
Thank you in advance for the help.
What is happening is your functions are executing as soon as you are trying to assign the event handler.
Any function with (); after it will get executed.
You can use the concept of closures and return a new function. Use a function wrapper which returns a new function for each of your tag.
a.onclick = filter(a.id);
b.onclick = filter(b.id);
c.onclick = filter(c.id);
d.onclick = filter(d.id);
e.onclick = filter(e.id);
function filterWrapper(tag) {
var tagValue = tag;
return function filter() {
let tag = tagValue;
for (var i = 0; i < x.length; i++)
if (tag === "view all") {
x[i].style.display = "block";
}
else {
if (tag.toLowerCase() === x[i].getAttribute('alt').toLowerCase())
x[i].style.display = "block";
else
x[i].style.display = "none";
}
return false;
}
}
}
Obviously, you could have fetched the value of id attribute inside the function itself. this inside event handler belongs to the element itself.
a.onclick = filter;
b.onclick = filter;
c.onclick = filter;
d.onclick = filter;
e.onclick = filter;
function filter() {
let tag = this.getAttribute('id');
for (var i = 0; i < x.length; i++)
if (tag === "view all") {
x[i].style.display = "block";
}
else {
if (tag.toLowerCase() === x[i].getAttribute('alt').toLowerCase())
x[i].style.display = "block";
else
x[i].style.display = "none";
}
return false;
}
}