I have been working on a website for a company and managed to make an element move as you scroll using jQuery. However, I've run into an issue where the movement of the element is causing excessive horizontal scrolling because it keeps moving further down as you scroll.
Is there a way to restrict the scrolling once the element goes out of view? Or perhaps set a maximum distance that it can move? I feel like I've been staring at this for too long without finding a solution.
$(function () {
var window_width = $(window).width() - $('#square_scroll01').width();
var document_height = $(document).height() - $(window).height();
$(window).scroll(function () {
var scroll_position = $(window).scrollTop();
var object_position_left = window_width * ((scroll_position / document_height) * 3);
$('#square_scroll01').css({
'left': object_position_left
});
});
});
.hero {
background: url(https://source.unsplash.com/5U_28ojjgms/1600x900) center center no-repeat;
background-size: cover;
height: 100vh;
width: 100vw;
position: relative;
}
.hero-content {
position: absolute;
top: 20%;
}
.p1 {
color: #fff;
}
.p2 {
color: #000;
}
#square_scroll01 {
position: absolute;
left: 9.5%;
bottom: -1.8%;
height: 35px;
width: 35px;
border-radius:5px;
background: #7AC143;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="hero">
<div id="square_scroll01">
</div>
</section>
View JSFiddle here