Hide Menu on scroll down (but only after 50px) - javascript

This script makes it so when you scroll down in a browser the navigation bar disappears/hides behind the header. I was wondering if it was possible if instead it hid as soon as you scrolled down, hiding it after a user scrolls down a certain number of pixels (say 50px) to avoid touchy nav hiding on slightest scroll.
Thanks in advance for any direction.
// Nav scroll test
var prev = 0;
var $window = $(window);
var nav = $('#belowhead');
$window.on('scroll', function(){
var scrollTop = $window.scrollTop();
nav.toggleClass('hidden', scrollTop > prev);
prev = scrollTop;
});

You can put this inside your "window.on('scroll')" function:
if(scrollTop > 50) {
nav.addClass('hidden');
} else {
nav.removeClass('hidden');
}

2019 Update / Adjustment
The following could be useful for anyone else wishing to develop a header that disappears when you scroll down. I just finished making the following for a website I'm creating that required the top header to disappear when the user started scrolling, but then reappear when they start scrolling up; continuously applying this logic if you were to constantly keep scrolling up and down on the website.
For starters, a class is added to my header tag called nav-scrolled when the user scrolls past a certain point - 50px in this case. This new class can then be styled to change the background-color, add a box-shadow etc...
$(function() {
var header = $(".nav-container");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 50) {
header.addClass("nav-scrolled");
} else {
header.removeClass("nav-scrolled");
}
})
});
However, this only solved the problem of not being able to edit the headers styles if the user is scrolling from the top of the page - not anywhere on the site - the following fixes this.
var userScroll;
var scrollTop = 0;
var delta = 5;
var navHeight = $('header').outerHeight();
$(window).scroll(function(event){
userScroll = true;
});
setInterval(function() {
if (userScroll) {
hasScrolled();
userScroll = false;
}
}, 250);
The next step for me was to sequentially add and remove classes show-nav and hide-nav that had been styled to display and hide the navigation menu. The following checks whether the user has scrolled (up or down) to a value higher than my delta variable. If the user is beginning to scroll up on the website, the class show-nav is added and the header transitions in from the top of the page. If the user is scrolling down the page the class hide-nav is added, and the header is hidden.
function hasScrolled() {
var st = $(this).scrollTop();
// Ensures a higher scroll than $delta
if(Math.abs(scrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > scrollTop && st > navHeight){
// Scroll Down
$('header').removeClass('show-nav').addClass('hide-nav');
$('.nav-toggle').removeClass('open');
$('.menu-left').removeClass('collapse');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('hide-nav').addClass('show-nav');
}
}
scrollTop = st;
}

Related

How to 'prioritise' a vanilla javascript if statement?

Currently experimenting for the first time with javascript. I'm trying to make a simple nav bar that disappears when the user scrolls down, reappears when they scroll up and does the same for when the mouse is in/out of the nav bar's area. Good news! Got that bit done.
The trouble comes when I then scroll up to make the nav bar appear, I move my mouse to click on it and then obviously a mouse event is triggered with the mouse outside of the hotspot and makes the nav bar disappear while you're on your way to it. It does reappear when I'm at the top with the mouse, but I'd like it to stay there once I've scrolled up to make it appear.
I have two if statements, one for the scroll and one for the mouse position. I'd like to make the site prioritise the effect of the scroll if statement over the mouse if statement.
This is the code I've stuck together after reading a hell of a lot of articles:
// Hide nav when scrolling down, show nav when scrolling up
var scrollCtrl = false;
var navbar = document.getElementById("navbar");
var prevScrollPos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollPos > currentScrollPos) {
navbar.classList.add('show');
var scrollCtrl = true;
} else {
navbar.classList.remove('show');
var scrollCtrl = false;
}
prevScrollPos = currentScrollPos;
}
// Get the height of the nav bar
var navHeight = getComputedStyle(document.getElementById("navbar")).height;
navHeight = navHeight.substring(0, navHeight.length -2);
navHeight = parseInt(navHeight, 10);
// Show nav when mouse is at the top
window.addEventListener('mousemove', function(e) {
var ypos = e.y;
if (ypos <= navHeight && scrollCtrl == false) {
navbar.classList.add('show')
}
else {
navbar.classList.remove('show')
}
});
What I've tried to do is use a boolean called scrollCtrl (because I want the scroll to be in control over the mouse position) but no matter what tweaks I make, I can't seem to get it to work.
The show/hide classes are just a CSS transform.
I am quite new to javascript, so please excuse any etiquette faux pas's!

How can I fix a div under my original header if it changes height when scrolling?

I created an additional menu bar (.secondnav) that I want to place right below the original header (#headAnnouncementWrapper) in a website. The problem is, when scrolling, the header's height changes when going from relative position to fixed at the top, and also when on mobile.
I've been trying with this:
var scrolled = 78;
var headHeight = $('#headerAnnouncementWrapper').height();
$(window).scroll(function() {
if ($(window).scrollTop() > scrolled) {
$('.secondnav').css('position', 'fixed');
$('.secondnav').css('top', headHeight);
} else {
$('.secondnav').css('position', 'relative'),
$('.secondnav').css('top', headHeight);
}
});
But I don't know how I should be calculating the headHeight variable so it changes when the height changes, and how to use that result as the top value for the .secondnav's css.
Check the height of the main header inside the scroll event. Each time the scroll event triggers, it will recheck the height. Then, the next line will adjust the top margin of the lower header to match the height of the upper header. Top-margin here replaces your position method.
var scrolled = 78;
$(window).scroll(function() {
var headHeight = $('#headerAnnouncementWrapper').height();
$('.secondnav').css('marginTop', headHeight);
if ($(window).scrollTop() > scrolled) {
$('.secondnav').css('position', 'fixed');
} else {
$('.secondnav').css('position', 'relative'),
}
});

Show menu on scroll up and also hide menu when it reach the top

Hi I have already made the navigation menu to show when scrolling down and hide it on initial load but after scrolling back to top the navigation menu is still showing.
I also wanted it to hide when scroll has already reached the top.
Here's my
$(document).ready(function(){
/** ===========================================
Hide / show the master navigation menu
============================================ */
// console.log('Window Height is: ' + $(window).height());
// console.log('Document Height is: ' + $(document).height());
var previousScroll = 0;
$(window).scroll(function(){
var currentScroll = $(this).scrollTop();
/*
If the current scroll position is greater than 0 (the top) AND the current scroll position is less than the document height minus the window height (the bottom) run the navigation if/else statement.
*/
if (currentScroll > 0 && currentScroll < $(document).height() - $(window).height()){
/*
If the current scroll is greater than the previous scroll (i.e we're scrolling down the page), hide the nav.
*/
if (currentScroll > previousScroll){
window.setTimeout(hideNav, 100);
/*
Else we are scrolling up (i.e the previous scroll is greater than the current scroll), so show the nav.
*/
} else {
window.setTimeout(showNav, 100);
}
/*
Set the previous scroll value equal to the current scroll.
*/
previousScroll = currentScroll;
}
});
function hideNav() {
$("[data-nav-status='toggle']").removeClass("is-visible").addClass("is-hidden");
}
function showNav() {
$("[data-nav-status='toggle']").removeClass("is-hidden").addClass("is-visible");
}
});

slideToggle is animating the div up and down continuously

I am using slideToggle to make my header move with the page once scrollTop hit the 100. But once the scrollbar reaches to 100 and more, it keeps animating up and down for few moment.
Here is my code:
$(window).scroll(function(){
var ScrollTop = $(window).scrollTop();
if(ScrollTop>=100){
$('#main_header').removeClass("relative");
$('#main_header').addClass("fixed");
$('#main_header').slideToggle("slow");
}else if(ScrollTop<=99){
$('#main_header').removeClass("fixed");
$('#main_header').addClass("relative");
}
});
please let me know what's wrong?
You are saying to the browser, whenever the user scrolls down the page, see how far they have travelled. If they have travelled more than 99, then slide that header, otherwise do some other class toggling.
So let's say they scroll to 120, it will slide. Then they scroll down more to 140, it will slide. You have no check in place on whether it has already slid down, thus it will keep doing it. A simple approach would be to just add a boolean: -
var toggled = false;
$(window).scroll(function () {
var ScrollTop = $(window).scrollTop();
if (ScrollTop >= 100 && !toggled) {
$('#main_header')
.removeClass("relative")
.addClass("fixed")
.stop() // stop any prev animation
.css('display', 'none') // force hide so it slides
.slideToggle("slow");
toggled = true; // won't enter again until set to false
} else if (ScrollTop <= 99 && toggled) {
$('#main_header').removeClass("fixed");
$('#main_header').addClass("relative");
toggled = false; // scrolled back up, can now slideToggle again!
}
});
Use jQuery .stop() method:
$(window).scroll(function(){
var ScrollTop = $(window).scrollTop();
if(ScrollTop>=100) {
$('#main_header').removeClass("relative");
$('#main_header').addClass("fixed");
$('#main_header').stop(true).slideToggle("slow");
} else if(ScrollTop<=99) {
$('#main_header').removeClass("fixed");
$('#main_header').addClass("relative");
}
});

Add Class only on browser Scroll Up

Is there any way to add class to an element only when someone scrolls the browser page up?
Problem Filide>>
JS
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll <= 100) {
$(".nav").addClass("darkHeader");
} else {
$(".nav").removeClass("darkHeader");
}
});
Problem is this js add class when scroll-down page. But I want to add class when Scroll Up browser and after that when scroll down class will remove. See Example demo>>
If you want to know whether the user has scrolled up or down you need to track of the last scroll position. Then check if the new scroll position is greater or less than that position. You can then set the classes accordingly
// Script
lastScroll = 0;
$(window).on('scroll',function() {
var scroll = $(window).scrollTop();
if(lastScroll - scroll > 0) {
$(".nav").addClass("darkHeader");
} else {
$(".nav").removeClass("darkHeader");
}
lastScroll = scroll;
});
JSFiddle

Categories