Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 398
Erwin van Ekeren Avatar asked Oct 10 '13 08:10

Erwin van Ekeren


People also ask

How do you get a scroll bar to margin top?

The scroll-margin-top property is used to set all the scroll margins to the top of an element at once.

What is scroll padding top?

The scroll-padding-top property defines offsets for the top of the optimal viewing region of the scrollport: the region used as the target region for placing things in view of the user.

How do you remove the top margin?

Adjusting the Margin Size of an HTML Element With CSS You can remove this margin by setting the top and left margin to zero. Like the padding and border, the sizes of specific sides of the margin can be set using margin-left , margin-right , margin-top , and margin-bottom .

What is scroll padding?

The scroll-padding shorthand property sets scroll padding on all sides of an element at once, much like the padding property does for padding on an element.


2 Answers

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');
});
like image 133
naththedeveloper Avatar answered Sep 19 '22 15:09

naththedeveloper


Do it like this

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

Demo Fiddle

like image 37
Vinay Pratap Singh Bhadauria Avatar answered Sep 20 '22 15:09

Vinay Pratap Singh Bhadauria