Search code examples
jqueryincrementdecrement

limit x value during increment / decrement with jQuery previous & next button


There are previous and next buttons below the main image, there is x amount of photos (7 in this case), I need to limit the value that's being added to x amount so that it can be only within the range 1 to x (1 to 7 in this case).

Obviously when user reaches x, clicking on next should go back to 1.

Problem can be seen here: http://mylandscapes.splintertaeal.com/gardens/regents-park.htm

Any help would be much appreciated.

Code:

$(document).ready(function () {
  var el = $('.nr');

  function change(amt) {
    el.text(parseInt(el.text(), 10) + amt);
  }

  $('#next').click(function () {
    change(1);
  });

  $('#prev').click(function () {
    change(-1);
  });
});

Solution

  • I'd say you should completely remove this code:

    $(document).ready( function() {
        var el = $('.nr');
        function change( amt ) {
            el.text( parseInt( el.text(), 10 ) + amt );
        }
        $('#next').click( function() {
            change( 1 );
        });
        $('#prev').click( function() {
            change( -1 );
        });
    });
    

    And instead modify the following event handler.

    var $nr = $(".nr");
    $('#next, #prev').on('click', function() {
        var A = this.id == 'next',X=A?T:0,Y=A?0:T,Z=A?N+1:N-1;N=N==X?Y:Z;
        $("#display").html('<img src="'+$(E[N]).attr('href')+'" />');
        $(".display2").html('<img src="'+$(F[N]).attr('href')+'" />');
        /* Update the slide number */ 
        $nr.text(N + 1);
    });
    

    No need to have two event handlers in this case.