Reputation: 11
I have some jquery code that detects a hover/unhover and moves the navbar in/out of view, the idea is that this only happens if the last scroll was a down scroll so I check what the last scroll was and use an if statement to determine whether or not to run the hover. The problem is the hover code is running no matter what the last scroll direction was.
I am clearly doing something wrong here, any help would be greatly appreciated.
This is my jquery code:
var lastScrollTop = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$("nav").hover(function() {
var header = document.querySelector('nav');
header.style.transform = 'translateY(0px)'
header.style.opacity = '100%'
}, function() {
var header = document.querySelector('nav')
header.style.transform = 'translateY(80px)'
header.style.opacity = '40%'
});
console.log("down");
} else {
console.log("up");
}
lastScrollTop = st;
});
Upvotes: 0
Views: 150
Reputation: 69
You can write the code this way. On scroll event you check for the 'offsetTop' for the 'nav'. And then check window 'pageYOffset' in condition, if greater means user have scrolled down.
I believe this is what you want:
window.onscroll = function() {myFunction()};
var navbar = document.querySelector("nav");
var navTop = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= navTop) {
navbar.style.transform = 'translateY(80px)';
navbar.style.opacity = '40%';
} else {
navbar.style.transform = 'translateY(0px)';
navbar.style.opacity = '100%';
}
}
Upvotes: 1