I have implemented the following functionality, but I am encountering an issue where the selected navigation item does not get highlighted in red when using the next and previous buttons. I have also chosen not to use IDs on the panels to allow for flexibility in adding or removing them. Is there a more efficient way to code this?
$(function($) {
$(document).on('click', ".slidenav", function() {
$("span.slidenav").on('click', function() {
$(".panel").removeClass("active");
var newPanel = $(this).index();
$(".panel").eq(newPanel).addClass("active");
$("span.slidenav").removeClass("selected");
$(this).addClass("selected");
});
});
});
$(document).on('click', "#next", function() {
if ($('.active').next('.panel').length) {
$('.active').removeClass('active')
.next('.panel')
.addClass('active');
}
});
$(document).on('click', "#prev", function() {
if ($('.active').prev('.panel').length) {
$('.active').removeClass('active')
.prev('.panel,.slidenav')
.addClass("active");
}
});
.panel {
width: 300px;
height: 300px;
position: absolute;
display: none;
}
.panel:nth-child(1) {
background: #ddd;
}
.panel:nth-child(2) {
background: #ccc;
}
.panel:nth-child(3) {
background: #bbb;
}
.panel:nth-child(4) {
background: #aaa;
}
.active {
display: block;
}
.selected {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<nav>
<span class="slidenav selected">Panel 1</span>
<span class="slidenav">Panel 2</span>
<span class="slidenav">Panel 3</span>
<span class="slidenav">Panel 4</span>
</nav>
<hr>
<div id="prev">Prev</div>
<div id="next">Next</div>
<hr>
<div class="panel-wrap">
<div class="panel active">
Panel 1
</div>
<div class="panel">
Panel 2
</div>
<div class="panel">
Panel 3
</div>
<div class="panel">
Panel 4
</div>
</div>
You can view the complete codepen here