Selector CSS class specification

In my code, why doesn't the color switch to yellow? jQuery slideUp

returns a jQuery object, so I don't see a problem as to why this doesn't work.

$(document).ready(function () {

    $(".accordion h3:first").addClass("active");
    $('.accordion p:not(:first)').hide();

    $('.accordion h3').on('click', function (e) {
        $(this).next('p')
            .slideToggle('slow')
            .siblings('p:visible')
            .slideUp('slow')
            .toggleClass('active')
            .siblings("h3").removeClass("active");
    });

});
      

.accordion {
  width: 480px;
  border-bottom: 1px solid #c4c4c4;
}
.accordion h3 {
  background: #e9e7e7 url(images/arrow-square.gif) no-repeat right -51px;
  font: bold 120%/100% Arial, Helvetica, sans-serif;
  padding: 7px 15px;
  margin: 0;
  border: 1px solid #c4c4c4;
  border-bottom: none;
  cursor: pointer;
}
.accordion h3:hover {
  background-color: #e2e2e2;
}
.accordion h3.active {
  background-position: right 5px;
}
.accordion p {
  background-color: #f7f7f7;
  margin: 0;
  padding: 10px 15px 20px;
  border-left: 1px solid #c4c4c4;
  border-right: 1px solid #c4c4c4;
}
.accordion h3.active {
  background-color: yellow;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion">
  <h3 class='active'>Photos</h3>
  <p>Here are the photos of this person</p>
  <h3>About</h3>
  <p>About this person</p>
  <h3>Friends</h3>
  <p>Friends go here</p>
  <h3>Work Info</h3>
  <p>Work info goes here</p>
  <h3>Relationship Status</h3>
  <p>status goes here</p>
  <h3>Orientation</h3>
  <p>Orientation goes here</p>
</div>
      

Run codeHide result


View in JSFiddle

+3


source to share


1 answer


The reason for this line ..

.next('p') and .siblings('p:visible') 

      

Your chain already has 2 levels of depth, the items p

and the second selection are the p

items that are visible and you will switch the class for them insteadh3

One approach is to switch the class active

separately to the current oneh3

.slideUp('slow')
.end()
.siblings("h3").removeClass("active");
// Add active to the current class            
$(this).addClass('active');

      



Fiddle

You can also use end

that completes the most recent filtering process. Because you have selected the items twice p

already before the operation.

.slideUp('slow')
.end()
.end()
.toggleClass('active')
.siblings("h3").removeClass("active");

      

should also work.

Updated Fiddle

+4


source







All Articles