Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth scroller based on mouse position (Jquery)

HI!

I would like to create a Smooth scroller based on mouse position. The idea is to create a outer div with a fixed width. The content is very wide and has to be scrolled to left or right, based on the mouse position. It would be great if the content is 'infinite' or 'endless'. The content is a very wide image that repeats 'seamelesly'.

Can anybody help me by creating this in jQuery?

Thanx in advance!

Alex

like image 566
Alex Avatar asked Dec 07 '22 21:12

Alex


2 Answers

You can set the image as the background of the div and animate the background-position with jquery. (and because it got me interested, here is an implementation)

demo http://jsfiddle.net/gaby/72yhW/

html

<div class="backdrop">
    <div class="direction left"></div>
    <div class="direction right"></div>
</div>

css

.backdrop{
    position:relative;
    height:300px; /*could be anything really..*/
    width:400px; /*could be anything really..*/
    border:3px solid #6699ff;
    background: url('YOUR IMAGE PATH GOES HERE') 0 0 repeat-x;
}

.direction{
    position:absolute;
    width:50%;
    height:100%;
}
.left{left:0;top:0;}
.right{right:0;top:0;}

jquery

$(function(){
    var x=0,
        y=0,
        rate=0,
        maxspeed=10;
    var backdrop = $('.backdrop');

    $('.direction', backdrop).mousemove(function(e){
        var $this = $(this);
        var left = $this.is('.left');

        if (left){
            var w = $this.width();
            rate = (w - e.pageX - $(this).offset().left + 1)/w;
        }
        else{
            var w = $this.width();
            rate = -(e.pageX - $(this).offset().left + 1)/w;
        }
    });

    backdrop.hover(
        function(){
            var scroller = setInterval( moveBackdrop, 10 );
            $(this).data('scroller', scroller);
        },
        function(){
            var scroller = $(this).data('scroller');
            clearInterval( scroller );
        }
    );   

    function moveBackdrop(){
        x += maxspeed * rate;
        var newpos = x+'px '+y+'px';
        backdrop.css('background-position',newpos);
    }
});
like image 71
Gabriele Petrioli Avatar answered Dec 23 '22 08:12

Gabriele Petrioli


There are two existing awesome jQuery plugins that do exactly what you seek:

1) http://manos.malihu.gr/jquery-thumbnail-scroller

2) http://www.convergent-evolution.co.uk/resources/jquery-plugins/scrolling-carousel/

Number 1 is more refined in that it has a smoother scrolling action and can optionally highlight the current hovered over item.

like image 23
Peter Avatar answered Dec 23 '22 07:12

Peter