-1

Hi im working on animating an arrow in an accordion but it only animates the first row no matter which one i pick. I know its a target issue but can make this work. some help would be great!!

code pen here https://codepen.io/al-web-dev/pen/bGRXdyL

<div class="myDiv">
            <div class="row">
                <div class="col-4">Test</div>
                <div class="col-4 cheese">test 1</div>
                <div class="col-4">
                    <i class="fa fa-arrow-up" aria-hidden="true"></i>
                </div>
            </div>
            <div class="row">
                <div class="col-4">Test</div>
                <div class="col-4 cheese">test 2</div>
                <div class="col-4">
                    <i class="fa fa-arrow-up" aria-hidden="true"></i>
                </div>
            </div>
        </div>


   var myDiv = document.getElementsByClassName("row");

for (var i = 0; i < myDiv.length; i++) {
    myDiv[i].addEventListener("click", function (event) {
        let toggleAble = document.querySelector(".fa-arrow-up");
        let cheese = document.querySelector(".cheese");
        event.target.classList.toggle("yello");
        event.target.classList.toggle("arrow-down");
    });
}
  • You're adding an event listener in a loop. Use a closure. Check out this answer for an example: https://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values – slidjoe Oct 06 '21 at 09:03
  • Look good but im struggling to see how this can be translated onto my code.. is it a targeting issue? Do i need to use 'bind' – Alex Jefferis Oct 07 '21 at 12:47

1 Answers1

0

The code in your codepen and your example given here is different. I suggest settling on one version of the code if you're gonna ask for help.

The problem you were facing in your codepen example had to do with var toggleAble. You were query-selecting by a classname. .querySelector will only pick the first element from a list of elements it finds. That is why you've had only the first arrow react. Change document before your query selector method to myDiv[i] - the element you're looking for the arrow in. Like so:

for (let i = 0; i < myDiv.length; i++) {
  myDiv[i].addEventListener("click", function (event) {
    var toggleAble = myDiv[i].querySelector(".fa-arrow-up");
    toggleAble.classList.toggle("arrow-down");
  });
}

Oh and for some reason you've renamed the function parameter to myDiv, an already declared array of elements. I've changed it back to event for you.

slidjoe
  • 113
  • 1
  • 6