I have a page with a header and a content. When scrolling down, the header menu sticks to the top while the content has a kind of "parallax" effect (it moves up faster than the header does, which is what I need).
My small jQuery script works well for the "parallax" effect but when the scroll down is at its max, the content starts to stutter/lag. The script seems to keep on trying to move the content up continuously (at least with an Apple Magic Mouse), which creates this ungraceful side effect.
How can I prevent that ?
PS: I exaggerated the parallax effect in the JSFiddle in order to clearly show the stuttering issue.
PPS: make sure you have a scrollable page when testing (small browser height), otherwise, the effect and issue won't happen, of course.
//sticky header menu
$(window).scroll(function() {
if ($(document).scrollTop() > 92) {
if (!$('.fixed').length) {
$('.menu').addClass('fixed');
}
} else {
if ($('.fixed').length) {
$('.menu').removeClass('fixed');
}
}
});
// Parallax of content on scroll
var iCurScrollPos = 0;
$(window).scroll(function() {
iCurScrollPos = $(this).scrollTop();
$('.content').css('margin-top', -iCurScrollPos * 1.2 + 'px')
});
body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
background: #ccc;
}
header {
position: relative;
width: 100%;
background: #fff;
z-index: 1;
height: 146px;
}
.void {
position: relative;
width: 100%;
height: 100px;
}
.menu {
position: relative;
width: 100%;
height: 54px;
background: #aaa;
}
.fixed {
position: fixed;
left: 0px;
top: 0px;
}
img {
width: 100%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div class="void"></div>
<nav class="menu"></nav>
</header>
<div class="content">
<img src="https://farm8.staticflickr.com/7632/16990947835_3894284fd8_b.jpg">
</div>
JSFiddle
https://jsfiddle.net/v6g43mkL/1/
from jQuery parallax effect and lagging
No comments:
Post a Comment