Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript jquery click

Click function with class to work solely for the current selection

发布于 2020-03-27 10:16:25

I am having some difficulties getting a click function to work the way I am intending. When the user click the arrow next to the catalog name, subViewBoxExpand should appear for only that specific selection.

Does anyone see what I am doing incorrectly?

$('.arrow').click(function() {
  var i = $(this).next('.subViewBoxExpand'),
    t = $(this).addClass('active');
  i.toggleClass('active', !0).slideToggle(500).find('.subViewBoxExpand').animate({
    opacity: 1
  }, 1500) + t, $('.subViewBoxExpand').not(i, t).slideUp(800).prev().removeClass('active');
  //$('.subViewBoxExpand').toggleClass('active');
});
.subViewBoxExpand {
  display: none;
}

.subViewBoxExpand.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog A</span><span class="arrow"> ></span>
  <div id="totalProfileViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog B</span><span class="arrow"> ></span>
  <div id="totalFastViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>
Questioner
Paul
Viewed
182
guradio 2019-07-03 21:48
  1. Use .closest() and combine with .find() to get the selected/clicked element and its corresponding view box.

Note: the view box is not next to the clicked element

sample : $(this).closest('.catalogSubViewBox').find('.subViewBoxExpand')

UPDATE: Remove the class active that is also being toggled in view

$('.arrow').click(function() {
  var i = $(this).closest('.catalogSubViewBox').find('.subViewBoxExpand'),
    t = $(this).addClass('active');
  i.slideToggle(500).find('.subViewBoxExpand').animate({
    opacity: 1
  }, 1500) + t, $('.subViewBoxExpand').not(i).slideUp(800).prev().prev().removeClass('active');
  //$('.subViewBoxExpand').toggleClass('active');
});
.subViewBoxExpand {
  display: none;
}

.subViewBoxExpand.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog A</span><span class="arrow"> ></span>
  <div id="totalProfileViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>
<div class="catalogSubViewBox">
  <span class="catalogSubViewBoxTitle">Catalog B</span><span class="arrow"> ></span>
  <div id="totalFastViews"></div>
  <div class="subViewBoxExpand">
    <p>You did it!</p>
  </div>
</div>