Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Animate and positioning elements

I current have a div that has around 5 images floating left so they are side by side. Now i have this div inside a parent div with overflow:hidden and the width so that it can only fit 4 images in.

Everything works fine apart from the animation, i have two arrows for left and right, but lets say i press right twice it moves across as it would normally but then when i press left once it resets the divs normal position and continues,

$(".next").click(function(){
    $(".item_wrap").animate({right: "+=118px"}, 1500 );
    return false;
});
$(".prev").click(function(){
    $(".item_wrap").animate({left: "+=118px"}, 1500 );
    return false;
});

this is the code i am currently using.

like image 248
user1527354 Avatar asked May 01 '26 12:05

user1527354


1 Answers

...but lets say i press right twice it moves across as it would normally but then when i press left once it resets the divs normal position and continues

Well that's because you can't animate both left and right on the same element unless you actually want the element to be stretching (it won't stretch in your case though since you've probably set a static element width.) Instead you animate just one of them by adding and subtracting:

$(".next").click(function(){
    $(".item_wrap").animate({right: "+=118px"}, 1500 );
    return false;
});
$(".prev").click(function(){
    // Subtract from 'right' instead of adding to 'left'
    $(".item_wrap").animate({right: "-=118px"}, 1500 );
    return false;
});
like image 62
Hubro Avatar answered May 03 '26 02:05

Hubro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!