I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated.
My Objective:
I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is clicked, the current panel should hide and the previous panel should appear. The panels are indexed as 1, 2, and 3. If the current panel is the first one and "previous" is clicked, then the third panel should be displayed. The same logic should apply when clicking the "next" button. Below is the HTML and JS code I am currently using:
HTML:
<div class="panel-slider">
<div class="panel" id="1">
<div class="panel-header">News Update 1</div>
<div class="panel-body">
<img src="img/news-update.jpg" class="img-responsive" />Lorizzle pizzle ma nizzle dope amizzle, consectetuer crazy elit. Dope dope velizzle, fo shizzle my nizzle volutpizzle, shizzlin dizzle fo shizzle, gravida fo shizzle, arc</div>
</div>
<div class="panel hide" id="2">
<div class="panel-header">News Update 2</div>
<div class="panel-body">
<img src="img/news-update.jpg" class="img-responsive" />Lorizzle pizzle ma nizzle dope amizzle, consectetuer crazy elit. Dope dope velizzle, fo shizzle my nizzle volutpizzle, shizzlin dizzle fo shizzle, gravida fo shizzle, arc</div>
</div>
<div class="panel hide" id="3">
<div class="panel-header">News Update 3</div>
<div class="panel-body">
<img src="img/news-update.jpg" class="img-responsive" />Lorizzle pizzle ma nizzle dope amizzle, consectetuer crazy elit. Dope dope velizzle, fo shizzle my nizzle volutpizzle, shizzlin dizzle fo shizzle, gravida fo shizzle, arc</div>
</div>
<div class="panel-slider-controls"> <a href="#" class="pull-left">Prev</a>
<a href="#" class="pull-right">Next</a>
</div>
</div>
JS:
var panel_index = 1;
$(".panel-slider .panel-slider-controls a").click(function () {
var that = $(this);
$(".panel[id=" + panel_index + "]").addClass("hide");
if (that.text() == "Prev") {
panel_index--;
if (panel_index > 1) {
$(".panel[id='" + panel_index + "']").removeClass("hide");
} else {
$(".panel[id='3']").removeClass("hide");
}
} else { //it's Next
panel_index++;
if (panel_index < 3) {
$(".panel[id='" + panel_index + "']").removeClass("hide");
} else {
$(".panel[id='1']").removeClass("hide");
}
}
});
The Issue at Hand:
The behavior of the slider is unexpected and abnormal. You can see the problem in action through this fiddle.
Could someone please explain why this is happening and help me resolve the issue?
Note: It would be greatly appreciated if someone could assist in removing the hard-coded IDs and making the slider work seamlessly regardless of the number of div elements present. Thank you! :)