Reputation: 1227
I am simply trying to fade in an element (#topNav) on scroll when the user is scrolling down and then when the user scrolls back up and hits the scrollTop, fade it out. Fade in on scroll down; fade out on scroll up.
But, it is fading in on both directions?
What am I doing wrong?
function scrollFunc(e) {
if ( typeof scrollFunc.x == 'undefined' ) {
scrollFunc.x=window.pageXOffset;
scrollFunc.y=window.pageYOffset;
}
var diffX=scrollFunc.x-window.pageXOffset;
var diffY=scrollFunc.y-window.pageYOffset;
if(diffX<0){
// Scroll right
}
else if(diffX>0){
// Scroll left
}
else if(diffY<0){
// scroll down
$('#topNav').fadeIn();
}
else if(diffY>0){
// Scroll up
if(document.body.scrollTop === 0){
//reached top
$('#topNav').fadeOut();
}
}
else{
// First scroll event
$('#topNav').css('position','fixed').show().fadeIn();
}
scrollFunc.x=window.pageXOffset;
scrollFunc.y=window.pageYOffset;
}
window.onscroll=scrollFunc;
Upvotes: 0
Views: 95
Reputation: 184
I fixed this issue as I was trying to achieve the same thing. This depends on jQuery, however. I assume that you have jQuery linked already as you are using the fade functions.
$(document).ready(function() {
$(window).scroll( function(){
if($(window).scrollTop()>0){
$("#topNav").fadeIn();
}
else{
$("#topNav").fadeOut();
}
});
});
Upvotes: 1