Hiding and Showing navigation arrows based on scroll position

I have a horizontal list with arrows that navigate through it, and I’m trying to get the get the right arrow to disappear when it reaches the end (and the same for the left arrow). It’s works…..sort of. My issue is that there is an extra click needed to make them disappear, even though the click before it will reach the end of the list. Any advice would be greatly appreciated!

JsFiddle link

//Hide left at start
$('#lefty').hide();
//left arrow controls
$('#lefty').click(function(){
    if($('.container').scrollLeft() == 0)

        {$('#lefty').hide()}
    $('#righty').show();   
 $(".container").animate({scrollLeft: "-=100px"})
 })
//right arrow controls
$('#righty').click(function(){
    if ($('.container')[0].scrollWidth - $('.container').scrollLeft() == $('.container').width())
      {$("#righty").hide()}
    $('#lefty').show(); 
 $(".container").animate({scrollLeft: "+=100px"})
 })

Answer

You need to apply the conditional after the animation is finish, in the current code is evaluating the conditional with some value during the animation. Use this:

//Hide left at start
$('#lefty').hide();

//left arrow controls
$('#lefty').click(function(){

    $('#righty').show();   
    $(".container").animate({scrollLeft: "-=100px"}, "normal", function(){
        if($('.container').scrollLeft() <= 0){
            $('#lefty').hide();
        }
    });
});

//right arrow controls
$('#righty').click(function(){
    $('#lefty').show(); 

    $(".container").animate({scrollLeft: "+=100px"}, "normal", function(){
        if ($('.container')[0].scrollWidth - $('.container').scrollLeft() == $('.container').width()){
            $("#righty").hide();
        }
    });
});

Leave a Reply

Your email address will not be published. Required fields are marked *