user1054409
user1054409

Reputation: 1

Setting boundaries for .animate in Jquery

I have a rudimentary slider in Jquery consisting of a left_arrow and a right_arrow div, both of which control the 'left' value of my #screens div containing a long .png. Each screen is 543px in width.

$pr('#arrow_left').click(function () {
    $pr('#screens').animate ({"left": "+=543px"}, "fast"); 
});
$pr('#arrow_right').click(function () {
    $pr('#screens').animate ({"left": "-=543px"}, "fast");
});

The slide action works fine, but I want to set min and max values for #screens 'left' value so the arrows won't take the user beyond the image in either direction.

Upvotes: 0

Views: 1048

Answers (2)

Chris Haugen
Chris Haugen

Reputation: 817

Kai Qing's answer is awesome :) I made a variation of it for my own needs, and added jQuery for the max variable so it will change based on how many direct child <div>'s the slider has so you never have to edit it once it's set :)

I'll just leave the code snippet here incase someone needs it :p

$(document).ready(function(){
var max = 275 * $('.slider-wrap > div').length; //change div to whatever element wraps each individual piece of content you're sliding.
var current = 0;
$('.left').click(function () {
if(current < max){
    alert(current);
    current += 275;
    $(".slider-wrap").animate({marginLeft:current + 'px'},'slow'); 
    }
});
$('.right').click(function () {
if(current > 0){
    alert(current);
    current -= 275;
    $(".slider-wrap").animate({marginLeft:current + 'px'},'slow'); 
    }
});

});

Upvotes: 0

Kai Qing
Kai Qing

Reputation: 18843

var max = 543 * 10; //10 slides, for example
var current = 0;
$pr('#arrow_left').click(function () {
    if(current < 0)
    {
        current += 543;
        $pr('#screens').animate ({"left": current + "px"}, "fast"); });

    }
});

$pr('#arrow_right').click(function () {
    if(current > max)
    {
        current -= 543;
        $pr('#screens').animate ({"left": current + "px"}, "fast");

    }
});

Upvotes: 2

Related Questions