detect scroll direction
Tracking whether user is scrolling up or down the page. Attempting to replicate native mobile app functionality.
by bizamajig
HTML
<p>The scroll movement is smooth and animated as expected, I just wish there was a better way to track it; without making a million events at every pixel.</p>
<p></p>
<p>How can I prevent this?</p>
<input type="text" value="value">
CSS
body {
font-family: arial;
height: 800px;
}
input {
border: 5px solid lightblue;
border-radius: 40px;
padding: 40px 0;
height: 60px;
width: 250px;
text-align: center;
font-weight: 700;
font-size: 2em;
}
input:focus { outline: 0; }
.down {
color: #090;
}
.up {
color: #900;
}
p {
margin-bottom: 50px;
}
JavaScript
$(function () {
// show hide subnav depending on scroll direction
var position = $(window).scrollTop();
$(window).scroll(function () {
var scroll = $(window).scrollTop();
if (scroll > position) {
//only piece that matters
$('input')
.stop(true, false)
.animate({
'padding': '0'
}, 'slow')
.removeClass('up')
.addClass('down');
// scrolling downwards, only here for dev purposes
console.log('moving DOWN the page');
$('input').val('down');
} else {
//only piece that matters
$('input')
.stop(true, false)
.animate({
'padding': '40px 0'
}, 'slow')
.removeClass('down')
.addClass('up');
// scrolling upwards
console.log('moving UP the page');
$('input').val('up');
}
position = scroll;
});
});