Reputation: 3496
I want to open and close a two separate div one by one with same class.
The below example when I first click opentab
content 1 will open first time and second click content 2 will open second time.
Closing the div one by one as follow content 2 and content 1.
Comment for further clarification. Thanks in advance.
$(document).ready(function() {
$(".opentab").on('click', function () {
$('.tabcontent').toggle('show');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="opentab" id="opentab">Open tab</a>
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>
Upvotes: 0
Views: 261
Reputation: 21672
Because you'll need to know which "direction" you're going (i.e. if the next click should be opening or closing items), I'd suggest using a boolean variable to keep track. Let's call that isClosing
.
Logic-wise, you are always doing one of two things:
(Comments included in the code)
let isClosing = true; //We need to know if we're "closing" or "opening" the items
$(".opentab").on('click', function() {
$(".tabcontent").finish(); //Skip animations if pressed rapidly
const $elementToToggle = isClosing
? $('.tabcontent:visible').last() //If "closing", toggle the last visible
: $('.tabcontent:hidden').first(); //Otherwise, toggle the first hidden
$elementToToggle.toggle('show', () => { //Callback to wait for animation to complete
if (!$(".tabcontent:visible").length) isClosing = false; //All hidden, switch to "opening"
else if (!$(".tabcontent:hidden").length) isClosing = true; //All visible, switch to "closing"
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="opentab" id="opentab">Open tab</a>
<div class="tabcontent">Content 1</div>
<div class="tabcontent">Content 2</div>
<div class="tabcontent">Content 3</div>
<div class="tabcontent">Content 4</div>
Upvotes: 3
Reputation: 22323
Hide your second div
and your toggle work.
$('.tabcontent').eq(1).hide();
$(document).ready(function() {
$(".opentab").on('click', function() {
$('.tabcontent').toggle('show');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="opentab" id="opentab">Open tab</a>
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>
Alternative set counter with hide and use toggle.
//$('.tabcontent').eq(1).hide();
var counter = 0;
$(".opentab").on('click', function() {
$('.tabcontent').eq(counter).hide();
counter++;
if (counter > 1) // Reset counter
counter = 0;
$('.tabcontent').toggle('show');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="opentab" id="opentab">Open tab</a>
<div class="tabcontent">
Content 1
</div>
<div class="tabcontent">
Content 2
</div>
Upvotes: 0