Oussama Dooby Oussama Dooby - 4 months ago 43
Javascript Question

margin-left changes on scroll

To scroll from left to right I have this little javascript, that works really well.

window.onscroll=function() {
var scroll = window.scrollY;
$('#page').css('left', '-' + scroll + 'px');
}


But everytime I scroll once to right, and I scroll back to left, the margin of the content changes.
image

You can see that the scrollbar is at the top at both pictures.
The first one is before the scroll, and the second one is after I scrolled.

demo without pictures

Answer

Adding position:fixed doesn’t automatically position the element to the far left. You should add an initial left value for #page for consistent results, f.ex:

#page{ left:0 }

Although it looks like you want to have some more space to the left, so try something like:

var init = 200, // the initial left margin
    $page = $('#page').css('left', init);
window.onscroll = function() {
    $page.css('left', init-window.scrollY);
};