Shavez
Shavez

Reputation: 63

Select set of three li and display them on next or previous button

I have the following code :

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>

    </ul>


</div>
<button id="but1">left</button>
<button id="but2">right</button>

Css:

.firstSlide{
    color:blue;
}
.secondSlide{
    color:red;
}
.thirdSlide{
    color:green;
}
.show{
    display:block;
}
.hide{
    display:none;
}

Jquery:

$("#news ul").each(function(){
  $(this).find("li").slice(0,3).addClass("firstSlide show");  
  $(this).find("li").slice(3,6).addClass("secondSlide hide");
  $(this).find("li").slice(6,9).addClass("thirdSlide hide");
})

$("#but2").on('click',function(){

});

$("#but1").on('click',function(){

});

I need to display the next three li when i click on right button and previous three li when I click left button. Something like a content slider.

Upvotes: 0

Views: 89

Answers (1)

Howard Renollet
Howard Renollet

Reputation: 4739

There are better ways of doing this. This example is really simplified to help you understand what's happening, but it should help get you on the right track: http://jsfiddle.net/ps2s0m08/3/

<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
    </ul>
<button id="but1">left</button>
<button id="but2">right</button>

<script>
    $("ul").each(function () {
        $(this).find("li").slice(0, 3).addClass("first");
        $(this).find("li").slice(3, 6).addClass("second").hide();
        $(this).find("li").slice(6, 9).addClass("third").hide();
    })

    $("#but2").on('click', function () {
        if ($("li:visible").hasClass("first")) {
            $(".first").hide();
            $(".second").show();
        }
        else if ($("li:visible").hasClass("second")) {
            $(".second").hide();
            $(".third").show();
        }
        else if ($("li:visible").hasClass("third")) {
            $(".third").hide();
            $(".first").show();
        }
    });

    $("#but1").on('click', function () {
        if ($("li:visible").hasClass("first")) {
            $(".first").hide();
            $(".third").show();
        }
        else if ($("li:visible").hasClass("second")) {
            $(".second").hide();
            $(".first").show();
        }
        else if ($("li:visible").hasClass("third")) {
            $(".third").hide();
            $(".second").show();
        }
    });
</script>
</body>

Upvotes: 1

Related Questions