Tobias Tobias - 2 years ago 325
Javascript Question

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);


Answer Source

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);
            '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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download