Sam Skirrow
Sam Skirrow

Reputation: 3697

jQuery animate a responsive div right and left by it's width

I have made a slider on a page with left and right arrows. When it's viewed on a desktop site, the width is 800px, and on a mobile site it is 230px. There is a left and right button for the slider, I want to be able to move the slides left and right according to their width. i.e. if it is 800px wide, I want to slide it 800px to the left and right, and similar for when it is only 230px wide.

Here is my jQuery code:

var calc_width = $('#calc_viewport').width();
$("#calc_next").click(function(){
if($("#calc_container").position().left == -8000 ) 
    {return;}
else { 
    $("#calc_container").animate({
        left: '-=calc_width'
    }, 1000, 'easeOutExpo');
}
});
$("#calc_prev").click(function(){
if($("#calc_container").position().left >= 0 ) 
    {return;}
else { 
    $("#calc_container").animate({
        left: '+=calc_width'
    }, 1000, 'easeOutExpo');
}
});

The first if statements in each of these makes sure it stops at the first and last slide so a user can't keep sliding. Currently this doesn't slide at all. Can anyone see where I have gone wrong?

Upvotes: 0

Views: 778

Answers (1)

Swiffy
Swiffy

Reputation: 4693

Well for one these are wrong:

left: '+=calc_width'

They should be like so:

left: '+=' + calc_width + 'px'

Or else you're trying to set the left of the element to '+=calc_width' instead of something like 100px.

And since you're animating calc_container by it's width - why is calc_width calculated from calc_viewport? This should probably be:

var calc_width = parseInt($('#calc_container').outerWidth());

Upvotes: 2

Related Questions