Skip to content
Advertisement

How to display menu only when a user scrolls the page in WordPress

I am trying to create an effect where the menu is hidden and only shows up when the user begins to scroll. I can’t seem to find out why my code isn’t working. I have the following jQuery code:

JavaScript

I also have this code which I added into a custom plugin. Please note than I’m using a child theme. I created a folder /js and added the following file menu-hide-scroll.js.

JavaScript

CSS

JavaScript

I am a beginner and at this point I’m stuck hopefully someone would help me out.

Advertisement

Answer

There’s a couple issues and minor points I’d like to make.

First of all, you’ve code a weird “jQuery code” in your question. Does your .js file contain <script src="http://code.jquery.com/jquery-1.10.2.js"> /* … */ </script>? If so, that’s illegal, you should not have the <script> tags inside your JavaScript files.

Second, you should be probably be making use of the document.ready check before you start running any JS, you can pass the $ reference variable in that function argument. Then from there, you can check the $(window)‘s scroll status (and use > 0 instead of > 100 if you want to make sure it shows as they start scrolling. Something like this:

JavaScript

You didn’t post your CSS, but make sure the #top div is visible (like position: fixed; top: 0; or something, making sure it’s visible in the window, otherwise it will “show” but not be visible since it’s off screen).

Third, pedantic, you’ll probably want to make your file names a bit more arbitrary and related to the handle. Right now you call it child-theme-script but the file name would indicate the only thing it does is hide the menu related to scrolling. Future you will appreciate a bit more concise naming convention one way or the other!

Fourth, you don’t need to use wp_register_script() unless you’re doing fancy work like dequeueing/enqueueing the script only if certain shortcodes are on the page, other parameters are set/not set, etc. wp_enqueue_script() handles the script registration for you (note, I changed the file name and function name in this snippet):

JavaScript

Here’s a quick codepen example for you on the JavaScript side: https://codepen.io/xhynk/pen/XWbmbgm

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement