Esser
Esser

Reputation: 540

Move an image or element when user scrolls

I'm trying to figure out how to move an image on the scroll event. I used .animate, but that moves it all the way, even after the user lets go. I want it to stop when the user stops scrolling.

Upvotes: 5

Views: 28541

Answers (2)

Craighead
Craighead

Reputation: 519

Stack: Determine the direction of scroll

By using this, you can then use .animate

JSFiddle

var lastScrollTop = 0;
$("div").scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
    $('img').animate({top: '-=10'}, 10);
} else {
    $('img').animate({top: '+=10'}, 10);
}
lastScrollTop = st;
});

Disregard: If you would like the image to move with the page, add position: fixed; to the CSS.

Upvotes: 5

Arno
Arno

Reputation: 161

You could use

$(window).scroll(function() { $(image).position($(image).position().top + 10); });

depending on your CSS. If you could provide some code (in a jsFiddle), maybe I would be able to help you a bit better.

Upvotes: 0

Related Questions