0

На сайте имеется 12 блоков при нажатии на блок тот открывается т.е к нему добавляется класс active.

И вот в этом блоке есть ещё несколько кнопок и проблема в том, что если нажать на любую из них, то событие, которое стоит на этом блоке срабатывает и блок закрывается. кнопка конечно же успевает сработать. я попробовал использовать event.stopPropagation() на кнопки, окно перестало закрываться, но fancybox привязанный к этим кнопкам тоже перестал нормально работать)

js

var scrollPosition = null;
$('.js-o-card').on('click', function () {
  var $window = $(window);
  const scrollAnimationDuration = 1000;
  if (!$(this).hasClass('active-card')) {

    $(this).addClass('active-card');

    $('html,body').animate({
      scrollTop: $(".active-card .thumbnail").offset().top - $(window).height() / 3
    }, scrollAnimationDuration);

    scrollPosition = $window.scrollTop();
  } else {
    $(this).removeClass('active-card');

    $('html,body').animate({
      scrollTop: scrollPosition
    }, scrollAnimationDuration);

  }
});
$('.js-btn-fancy').click(function(){
  event.stopPropagation();
});

подскажите, как сделать так, чтобы такого не происходило?

1 ответ 1

1

Можно использовать event.target. Для примера:

$('.wrapper').click(function(e){    
  if (e.target.tagName !== 'BUTTON')
  $(this).toggleClass('active');
})

$('button').click(function(e){
    $(e.target).toggleClass('bg');
})
.wrapper {
  width: 200px;    
  background: blueviolet;
  overflow: hidden;
  color: white;
  padding: 10px;
}

.wrapper button{
  display: none;
  border: none;
  margin: 5px;
}
  

.wrapper.active button{
  display: block;
}

button.bg{
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">  
<h3>Card</h3>
  <button>Button1</button>
  <button>Button2</button>
  <button>Button3</button>
</div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.