Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery – move object horizontally on vertical scroll

This is more of a mathematical question than programming.

I want to move an object horizontally, from the left to the right edge of the browser window when the document is being scrolled.

Scroll position "0" should bring the object to the very left of the window and scroll position "down at the end of document" should bring the object to the very right of the window but not further.

I tried this but failed:

var window_width = $(window).width();

$(window).scroll(function () { 
    var scroll_position = $(window).scrollTop();
    var object_position_left = scroll_position*(scroll_position/window_width);

    $('#object').css({'left':object_position_left});
});

http://jsfiddle.net/BA5p4/

like image 664
Tobias Avatar asked Apr 16 '13 05:04

Tobias


1 Answers

See the demo in jsFiddle

var window_width = $(window).width() - $('#object').width();

var document_height = $(document).height() - $(window).height();

$(function () {
    $(window).scroll(function () {
        var scroll_position = $(window).scrollTop();
        var object_position_left = window_width * (scroll_position / document_height);
        $('#object').css({
            'left': object_position_left
        });
    });
});

You just need to move the object to left (based on window_width) with whatever percentage you scrolled down(based on document_height).

The window width and document height are adjusted to prevent object going outside the window.

You may need to recalculate these variables on window re-sizing.

like image 129
Sen Jacob Avatar answered Sep 28 '22 16:09

Sen Jacob