Jquery открытие не более одного попапа одновременно
Есть примитивный пример, где открываются окошки при клике на кнопку. Вопрос, как сделать, чтоб одновременно 2 окошка или более нельзя было открыть. То есть если одно открыто, то при открытие второго, чтоб первое закрывалось. Спасибо https://jsfiddle.net/e043pLzd/15/
$('.btn-opener').click(function() {
$(this).closest(".container-item").toggleClass('active');
});
.row {
display: flex;
}
.container-item {
position: relative;
}
.popup {
position: absolute;
left: 0;
top: 100%;
width: 100%;
background: #fff;
opacity: 0;
visibility: hidden;
border-radius: 10px;
box-shadow: 0 0 10px 0 #000;
width: 160px;
padding: 10px;
z-index: 10;
}
.container-item.active .popup {
opacity: 1;
visibility: visible;
}
.btn-opener {
background: blue;
color: #fff;
border-radius: 30px;
width: 200px;
display: flex;
align-items: center;
justify-content: center;
height: 40px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="container-item">
<div class="btn-opener">Я кнопка</div>
<div class="popup">я всплывающая тучка</div>
</div>
<div class="container-item">
<div class="btn-opener">Я кнопка 2</div>
<div class="popup">я всплывающая тучка 2</div>
</div>
<div class="container-item">
<div class="btn-opener">Я кнопка 3</div>
<div class="popup">я всплывающая тучка 3</div>
</div>
</div>
Ответы (2 шт):
Автор решения: Igor
→ Ссылка
$('.btn-opener').click(function() {
var wasOpen = $(this).closest(".container-item").hasClass('active');
$(".container-item.active").removeClass('active');
if (!wasOpen)
$(this).closest(".container-item").addClass('active');
});
Автор решения: Deonis
→ Ссылка
const containerItem = $(".container-item");
$('.btn-opener').click(function() {
let currentItem = $(this).closest(".container-item");
containerItem.not(currentItem).removeClass('active');
currentItem.toggleClass('active');
});
UPD Оптимальней даже так:
const containerItem = $(".container-item");
$('.btn-opener').click(function() {
let currentItem = containerItem.has(this);
containerItem.not(currentItem).removeClass('active');
currentItem.toggleClass('active');
});
Единожды кешируем все элементы .container-item и просто отфильтровываем по мере надобности.