Search code examples
jquerytraversal

disable next/prev at the start/end of the list


I want to be able to hide/disable the prev link when I am at the first box and disable the next link at the last box because at the moment you can keep clicking on next at the last box and when you do this it breaks as clicking previous no longer works. see demo in fiddle

<span id="wrapper">
<span id="prev"><a href="#">Go to Prev</a></span>
<span id="content">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
    <div id="start" class="box">6</div>
    <div class="box">7</div>
</span>
<span id="next"><a href="#">Go to Next</a></span>

    var $curr = $("#start");
$curr.css("display", "inline");
$("#prev a").click(function () {
  $curr = $curr.prev();
  $(".box").css("display", "");
  $curr.css("display", "inline");
});

$("#next a").click(function () {
  $curr = $curr.next();
  $(".box").css("display", "");
  $curr.css("display", "inline");
});

Solution

  • I would do it this way:

    http://jsfiddle.net/mBXYL/

    var $curr = $("#start");
    $curr.css("display", "inline");
    $("#prev a").click(function() {
        $curr = $curr.prev();
        $(".box").css("display", "");
        $curr.css("display", "inline");
        $("#next").show();
        if (!$curr.prev().length) {
            $("#prev").hide();
        }
    });
    
    $("#next a").click(function() {
        $curr = $curr.next();
        $(".box").css("display", "");
        $curr.css("display", "inline");
        $("#prev").show();
        if (!$curr.next().length) {
            $("#next").hide();
        }
    });​