Search code examples
javascriptjqueryjslider

Simple Jquery slider, do not want to use plugin


I have the following code, I have implemented something like this so far, but I want to add "NEXT" "PREV" functionality to this, for which I need suggesstion.

<div id="slider">
<div class="wrap"> 
<div class="panel">Panel1</div> 
<div class="panel">Panel2</div> 
<div class="panel">Panel3</div>
</div>

<div class="previous">This need Implementation</div>
<div class="next">This need Implementation</div>

</div>

<div class="nav">

<ul>
<li> panel1</li>
<li> panel2</li>
<li> panel3</li>
<ul>

</div>


$(document).ready(function () {

$(".wrap .panel:not(.active)").fadeOut();
$(".wrap .panel:first(.active)").fadeIn();

$(".nav ul li").click(function (event) {

$(this).addClass('current').siblings().removeClass('current');

$(".wrap .panel").stop(true, true).fadeOut().eq($(this).index()).fadeIn();

});
});

Solution

  • you need to store the index of the current pane displayed

    var currentIndex = 0;// store current pane index displayed
    var ePanes = $('#slider .panel');// store panes collection
    function showPane(index){// generic showPane
        // hide current pane
        ePanes.eq(currentIndex).stop(true, true).fadeOut();
        // set current index : check in panes collection length
        currentIndex = index;
        if(currentIndex < 0) currentIndex = ePanes.length-1;
        else if(currentIndex >= ePanes.length) currentIndex = 0;
        // display pane
        ePanes.eq(currentIndex).stop(true, true).fadeIn();
        // menu selection
        $('.nav li').removeClass('current').eq(currentIndex).addClass('current');
    }
    // bind ul links
    $('.nav li').click(function(ev){    showPane($(this).index());});
    // bind previous & next links
    $('.previous').click(function(){    showPane(currentIndex-1);});
    $('.next').click(function(){    showPane(currentIndex+1);});
    // apply start pane
    showPane(0);