Reputation: 150
I have trouble finding a code that says if this site is scrolled down I want a div to move upwards at the same time, until I have scrolled past certain amount of pixels.
So if I scroll down like 100pixels, my div move upwards 100pixels, and when I pass by 120pixels the functions stops. When I scroll upwards again the function starts again but of course, the opposite effect.
Right now I have this code but I want it to be smooth and pixel by pixel, not just the effect when the poisiton is right.
$(window).scroll(function(){
var a = 145;
var pos = $(window).scrollTop();
if(pos > a) {
$("#mobil .holder").css({
top: '0'
});
}
else {
$("#mobil .holder").css({
top: '145px'
});
}
});
Upvotes: 0
Views: 398
Reputation: 32581
You can use animate for the smoothness and check if pos is larger than 120 like this
$(window).scroll(function () {
var pos = $(this).scrollTop();
$('div').stop().animate({
top: (pos >=120?120:pos)
}, 1000);
});
Upvotes: 1
Reputation: 33880
Just use that :
$(window).scroll(function(){
var a = 145;
var pos = $(window).scrollTop();
$("#mobil .holder").css({
top: -(Math.min(pos, 145))
});
});
It negate the value of scroll top since you want it to move upward. The Math.min()
is used to set a limit. It will never go above 145px.
Upvotes: 2