Erwin van Ekeren
Erwin van Ekeren

Reputation: 730

change margin-top on scroll

i have a negative margin on a div, but I want to change the negative margin on scroll till the negative reaches 0.

from:

margin:-150px 0 0 0;

to: (on scroll)

margin:0px 0 0 0;

i think it's some kind of parallax effect where i'm searching for and found this on StackOverflow: Change margin top of div based on window scroll

i thought of something like this but there must be something easier

$(window).scroll(function(){
if  ($(window).scrollTop() >= 1){ $('#three').css({margin:'-149px 0 0 0px'}); }
if  ($(window).scrollTop() >= 2){ $('#three').css({margin:'-148px 0 0 0px'}); }  
if  ($(window).scrollTop() >= 3){ $('#three').css({margin:'-147px 0 0 0px'}); }   
if  ($(window).scrollTop() >= 4){ $('#three').css({margin:'-146px 0 0 0px'}); }  
else { $('#three').css({margin:'-150px 0 0 0px'}); }
});

--

i created a fiddle with the html / css basis

fiddle: http://jsfiddle.net/qSe4e/

--

thank you so much in advanced

Upvotes: 8

Views: 24732

Answers (2)

ɴᴀᴛᴇ ᴅᴇᴠ
ɴᴀᴛᴇ ᴅᴇᴠ

Reputation: 4611

Try using a little bit of math to automatically generate all of the possibilities (similar to your attempt but with a single line instead of one for each possibility.

Example: http://jsfiddle.net/qSe4e/9/

$(window).scroll(function(){
    var fromTop = $(window).scrollTop();
    $("#three").css('margin', '-' + (100 - fromTop) + 'px 0px 0px 0px');
});

Upvotes: 9

Do it like this

$(document).scroll(function () {
$("#three").animate({margin: "0px 0px 0px 0px"}, 3000);
});

Demo Fiddle

Upvotes: 1

Related Questions