Using Arrow Buttons To Scroll Window Horizontally

user2634764 picture user2634764 · Aug 6, 2013 · Viewed 22.6k times · Source

Basically I have a website with horizontally scrolling content. As in the whole page scrolls horizontally, not just a div.

I am trying to implement left and right arrow buttons that onmousedown or hover (it doesn't matter too much which one yet), scrolls the whole window (smoothly) left and right.

This website does pretty much what I want with the little centred arrows: http://www.clholloway.co.za

Can anyone help with this? Cheers.

Answer

Josh picture Josh · Aug 6, 2013

I think with a little bit of jQuery you can achieve what you are looking for. The basic idea is to handle some event (onmouseenter, mousedown, etc...) that you can then use to kick off the scrolling.

Imagining you have some markup that looks like this:

<div id="parent">
    <div class="contentBlock">1</div>
    <div class="contentBlock">2</div>
    <div class="contentBlock">3</div>
    <div class="contentBlock">4</div>
    <div class="contentBlock">5</div>
</div>
<span id="panLeft" class="panner" data-scroll-modifier='-1'>Left</span>

<span id="panRight" class="panner" data-scroll-modifier='1'>Right</span>

And a few styles to ensure it will cause the window to scroll:

#parent {
    width:6000px;
}
.contentBlock {
    font-size:10em;
    text-align:center;
    line-height:400px;
    height:400px;
    width:500px;
    margin:10px;
    border:1px solid black;
    float:left;
}
.panner {
    border:1px solid black;
    display:block;
    position:fixed;
    width:50px;
    height:50px;
    top:45%;
}
.active{
    color:red;
}
#panLeft {
    left:0px;
}
#panRight {
    right:0px;
}

You can use a combination of styling, setInterval, and jQuery.scrollLeft() to achieve the effect you want.

(function () {

    var scrollHandle = 0,
        scrollStep = 5,
        parent = $(window);

    //Start the scrolling process
    $(".panner").on("mouseenter", function () {
        var data = $(this).data('scrollModifier'),
            direction = parseInt(data, 10);        

        $(this).addClass('active');

        startScrolling(direction, scrollStep);
    });

    //Kill the scrolling
    $(".panner").on("mouseleave", function () {
        stopScrolling();
        $(this).removeClass('active');
    });

    //Actual handling of the scrolling
    function startScrolling(modifier, step) {
        if (scrollHandle === 0) {
            scrollHandle = setInterval(function () {
                var newOffset = parent.scrollLeft() + (scrollStep * modifier);

                parent.scrollLeft(newOffset);
            }, 10);
        }
    }

    function stopScrolling() {
        clearInterval(scrollHandle);
        scrollHandle = 0;
    }

}());

Full jsFiddle demonstrating this approach: http://jsfiddle.net/jwcarroll/atAHh/