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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With