jQuery on click event fires to many times with grid

0
I have a simple accordion functionality using jQuery's slideToggle when one item in a grid is clicked. When clicked the content of the grid slides down. The problem i'm having, is that there's something wrong with the click handling. Right now there are 3 items in the grid. When I click the top one the slideToggle event is called three times. so open>close>open when I click the second item it fires twice : open>close On the third one it works as supposed to so : open I think it has something to do with the fact that the class names of the three divs that need to slide are the same. Any tips or solutions for this problem?
asked
1 answers
0

You can solve this by investigating the click target when a click occurs. Find out what was clicked, then use that DOM element to find the right element to show/hide. I built a widget that does something like this, though it's not very flexible in its current form. Here's the relevant code:

        $(document).on('click.' + this.id, '.toggleButton', function() {
            $(this).toggleClass("fa-caret-right fa-caret-down");
            $(this).parent().parent().next().slideToggle("fast");
        });

The object "this" inside the event listener will be the actual DOM element clicked. This code looks at the clicked item, its grandparent's next sibling in the DOM, and performs a slideToggle on that element.

Here's my widget's gitHub repository: https://github.com/tieniber/ShowHideDivButton/

answered