jQuery doubt all elements are affected by the function

Asked

Viewed 31 times

0

I have the following function, which works to change the arrow of an accordon when it is active (open), arrow down to reverse up, and then return to the original state, but all arrows are affected, and not only the one I am clicking at the moment, How can I fix this? I tried to use this but it didn’t work for this situation:

 function controlAccordeon() {
    var accordeonTitle = $('.accordeon-open-title');
    var angleDown = $('.fa-angle-down');
    var angleUp = $('.fa-angle-up');

    accordeonTitle.click(function() {
        $(this).toggleClass('active');
        angleUp.toggleClass('hide');
        angleDown.toggleClass('hide');
    });
}
  • angleUp.toggleClass('hide'); and angleDown.toggleClass('hide'); has to be done by navigating in html and not in this way but it hits all. Showing the corresponding html helps to get the correct answer

  • Put an id on the element you want to move and call it id instead of class

2 answers

1


if angleDown and angleUp are daughters of the accordeonTitle just call from within the click function $('.fa-Angle-up',this). toggleClass('Id'); but without seeing the html there is no helping much.

  • that’s exactly what it was, it worked, thank you !

1

The rule is: collect all but what was clicked, this gets toggle.

I also suggest controlling the arrows with CSS, so you only need to change the class active and the rest "happens for you".

Example:

function controlAccordeon() {
  var accordeonTitle = $('.accordeon-open-title');

  accordeonTitle.click(function() {
    accordeonTitle.not(this).removeClass('active');
    $(this).toggleClass('active');
  });
}

controlAccordeon();
* {
  margin: 0;
  padding: 0;
}

.accordeon-open-title {
  height: 30px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid black;
  padding: 10px;
  border-radius: 5px;
  transition: height .8s;
}

.accordeon-open-title.active {
  height: 200px;
}

/* setas */

.accordeon-open-title .fa-angle-down {
  transform: rotate(0deg);
  transition: transform 0.8s;
}

.accordeon-open-title.active .fa-angle-down {
  transform: rotate(-180deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<div class="accordeon-open-title">
  <h1>Titulo 1 <i class="fa fa-angle-down"></i></h1>
  <p>Conteúdo</p>
</div>
<div class="accordeon-open-title">
  <h1>Titulo 2 <i class="fa fa-angle-down"></i></h1>
  <p>Conteúdo</p>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.