Yogesh Chauhan's Blog

How to hide and show menu on scroll using JavaScript and CSS?

in CSS & JavaScript on May 11, 2021

The basic idea is to make use of position property from CSS and scrollY property of window interface from JavaScript.

Step 1: HTML

You need to have content larger than the browser window height otherwise you won’t be able to scroll and menu will be visible all the time.

Give the elements attributes like ID and class so that we can style them using CSS and get the menu using JavaScript.

Step 2: CSS

Let’s make everything look better using CSS. Also, you’d want to add position:fixed to the menu since we want it to kinda hang on to a specific part of the browser window.

I have top property set as 0 for the menu as well since I am sticking it to the top part. You can be flexible and set it to a bottom part and then change the login in the JavaScript to make that work.

transition property plays an important roles too since you’d want to make the toggle transition smoother.

Step 3: JavaScript

Till this point, you can scroll the content but the menu is fixed. So, all you need to do is get the scrolling position of the window and then based on that show or hide the menu.

We can either use scrollY property or pageYOffset property. They both get you the scrolled value (in pixels) of the current document along the vertical axis.

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to create a dynamic countdown using HTML and JavaScript?HTMLThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSHow to add Lifecycle Methods to a Class in React?ReactWhat is Prototypal Inheritance in JavaScript?JavaScriptKilling A Project Part 4: What Would Be Your Top 3 Priorities For Planning The Cancellation?MiscellaneousDROP DATABASE (remove a database) from PostgresPostgres