ngplayground ngplayground - 3 months ago 23
jQuery Question

jQuery to scroll a page on hover

jsFiddle

HTML

<div class="next">Next</div>
<div class="prev">Prev</div>


jQuery

$(function() {
$('ul.nav a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1000);
event.preventDefault();
});
});


The idea sounds simple but I can't get this working at all. I want to be able to scroll the page on hover of either next or prev. I have the click to scroll to anchor down but this added feature would be perfect to have.

Answer

Just a mockup you need to take care of the edge cases: http://jsfiddle.net/pBLAJ/11/

        $(function () {
            $('ul.nav a').bind('click', function (event) {
                var $anchor = $(this);
                $('html, body').stop().animate({
                    scrollLeft: $($anchor.attr('href')).offset().left
                }, 1000);
                event.preventDefault();
            });
            $('.next').on('mouseenter', rscroll);
            $('.prev').on('mouseenter', lscroll);
            $('.next,.prev').on('mouseleave', function () {
                $('body').stop();
            });

            function rscroll() {
                $('body').animate({
                    scrollLeft: '+=25'
                }, 10, rscroll);
            }

            function lscroll() {
                $('body').animate({
                    scrollLeft: '-=25'
                }, 10, lscroll);
            }
        });
Comments