Update:
Seems like the problem has nothing to do with my code. I've been running the webpage over browser-sync and that's where the problem appears. When I open the static webpage in Chrome directly, everything seems to be working fine. Thank you to everyone for your help!
I'm working on my personal website and want to make a way to filter through my list of projects using buttons.
<div class="filters">
<button class="btn btn-filter">Android</button>
<button class="btn btn-filter">iOS</button>
<button class="btn btn-filter">Web Dev</button>
<button class="btn btn-filter">Data Science</button>
</div>
I'm trying to attach event listeners to the buttons by doing this, but it seems like the event listeners are being attached multiple times:
$(".btn-filter").each(function() {
console.log(this); // #1
$(this).click(function(e) {
e.preventDefault();
e.stopPropagation();
console.log(this); // #2
})
debugger;
})
I have also tried using the class selector. It doesn't work, I switched to .each()
and $(this)
to be sure the elements were being assigned event handlers only once.
$('.btn-filter').click(...)
Logs show that each button is selected once to be assigned a click listener, but when I actually click the buttons, only some fire once, and some fire 3 times. I use some because it doesn't always behave the same way each time the page is run.
I have tried the solutions described in
this post(off()
, unbind()
, stopPropagation()
), but none have worked.
Using Google Chrome's debugger tools, it seems like at the breakpoint, this
refers to the HTML element twice for every iteration of each, despite some clicks firing once and some three times.
I suppose I could just assign IDs and wire each button individually, but I want to know what I'm doing wrong here. Could anyone explain?
".btn-filter"
you already select all the buttons (with that class) and can bind one handler to all of them.each()
andthis
to debug$(".btn-filter").each()
being called multiple times, for instance inside another event handler?