I am trying to make a bootstrap panel slider. For which I have written my own jQuery code, which is not working as expected.
What I am trying to do:
I have two links for previous and next and I have 3 panels with different headings just for distinction between the three. On click of previous, the current panel should hide and it's previous panel shoudl come up. I have indexed the panels by IDs 1, 2 and 3. If the current panel is the first one and previous is clicked then the last one, the third one should pop up. And vice versa when we click the next button. The following is my code that I am 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");
}
}
});
What's happening:
The behaviour is abnormal. It's not working as expected. It's unexplainable, see this in this fiddle.
Why is this happening? Can someon please help?
Note: If someone could remove my hard-coded IDs and could just make it work for no matter how many number of div, it would be great, thanks. :)