StickyJS is used is to create a sticky menu-bar (among other things).
A menu-bar is normally present at the top of a site/page. So, when the user scrolls down the page, the menu bar is no longer in the visible area of the screen, making it difficult for the user to navigate the site.
A sticky menu-bar on the other hand, sticks to the top of the browser when the user scrolls past the menu bar. This means that the menu-bar is always visible to the user who can then easily move around the site.
An example is the menu-bar on this site.
The download contains several examples of how stickyJS may be used but none of them describe how to integrate it with a WordPress site. I intend to fill up this gap through this post.
As a first step, you need to import the JS file(s) into WordPress. The main JS which contains the actual functionality is in a file called ‘jquery.sticky.js’.
Hence, this file must be imported through the ‘functions.php’ file of your WordPress theme and the safest way to do so is to use the ‘wp_enqueue_script’ function of WordPress, such as below:
There is another piece of JS code that is used to run/call ‘jquery.sticky.js’. This piece of code may be placed in separate file and imported the same way as described above.
However, using the code exactly as it comes with the downloaded example gives the following error: “$ is not a function”
To overcome this error, use the slightly modified code provided below:
This modification was based on the discussion here.
This should allow you to create a sticky menu-bar but problems arise if your theme is responsive where the site adapts with the screen size (width or height), for example when it is viewed on a mobile device. In this case, you cannot use a fixed width because the width of the menu bar must adapt with the width of the screen it is viewed on.
The way to overcome this problem is to use the code snippet below (which is a modification of the code above):
Here, ‘#main-navigation’ is the div that contains the menu-bar.
‘#container’ is the div that contains the site content and determines the width of the menu-bar.
For reference, the original discussion can be found here.
This is all you need to create a sticky menu-bar and the two reference links should provide additional information if required.
However, if any one has any further questions, feel free to leave those in the comments section below and I will try to address them as soon as possible.