I'm trying to move an element to left and right while scrolling up and down in this example FIDDLE the problem is the div will keep moving to reach out of the page and doesn't return to its original position. This is the example I'm trying to simulate Original Example
HTML
<div class='container'>
<div class='inner'>
</div>
</div>
JS
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
var offset = $(".inner").offset();
var w = $(window);
var x = offset.left;
console.log(x);
$(".inner").css("left",x+50);
} else {
var offset = $(".inner").offset();
var w = $(window);
var y = offset.left;
console.log(y);
$(".inner").css("left",y-50);
}
lastScrollTop = st;
});
CSS
.container{width:100%; position: relative; float:left; background:#fff; height:1200px;}
.inner{width:150px; height:100px; position:absolute; top:20%; left:10%; background:red;}
I'm trying to move an element to left and right while scrolling up and down in this example FIDDLE the problem is the div will keep moving to reach out of the page and doesn't return to its original position. This is the example I'm trying to simulate Original Example
HTML
<div class='container'>
<div class='inner'>
</div>
</div>
JS
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
var offset = $(".inner").offset();
var w = $(window);
var x = offset.left;
console.log(x);
$(".inner").css("left",x+50);
} else {
var offset = $(".inner").offset();
var w = $(window);
var y = offset.left;
console.log(y);
$(".inner").css("left",y-50);
}
lastScrollTop = st;
});
CSS
.container{width:100%; position: relative; float:left; background:#fff; height:1200px;}
.inner{width:150px; height:100px; position:absolute; top:20%; left:10%; background:red;}
Share
Improve this question
asked Jan 5, 2016 at 17:03
PHP UserPHP User
2,4226 gold badges52 silver badges99 bronze badges
1 Answer
Reset to default 5You need to offset it by the scrolled amount, not move it by an amount each time. You are queuing up multiple moves and adding 50px each time.
var offset = $(".inner").offset();
$(window).scroll(function(event) {
var st = $(this).scrollTop();
$(".inner").css("left", st + offset.left);
});
JSFiddle: https://jsfiddle/TrueBlueAussie/x0vtopzv/1/
Once it is locked to the scrolling, you can adjust the position using a multiplier on the st
value.
Note: JSFiddle has an 8px margin on the body
. That throws out the offset position and needs to be removed or taken into account.
https://jsfiddle/TrueBlueAussie/x0vtopzv/6/