You are here

How to create floating top bar or menu in Drupal using Jquery

In this blog we are going to share how we created a floating topbar on our company's website - www.sparxsys.com The moment you open the site, the topbar looks normal, just like any other site, but the moment you start scrolling the bar goes up, disappears and it comes back and stays on top for the rest of the site. It could be a great way to engage with your users and highlight certain links of your website.

Step 1: Copy the following code in your theme's js folder. In our case we use Omega4, so copy this js code at /omega_sub_theme/js/menu-scroll.js location.

  1. jQuery(document).ready(function(jQuery) {
  2.  
  3. var scrolled = false;
  4. jQuery(window).scroll(function() {
  5. console.log(jQuery(window).scrollTop());
  6. if ((jQuery(window).scrollTop() >= 270) && (scrolled === false)) {
  7. jQuery('.l-logobar').hide();
  8. jQuery('.l-logobar').addClass('fixed');
  9. jQuery('.l-logobar').fadeIn();
  10. scrolled = true;
  11. }
  12. else if (jQuery(window).scrollTop() < 270) {
  13. scrolled = false;
  14. jQuery('.l-logobar').removeClass('fixed');
  15.  
  16. }
  17. });

Basically this Javascript code will apply one extra class "fixed" to your region "l-logobar". The css for this extra class "fixed" need to be defined in your style.

Step 2: Tell your theme to load this Javascript file.

In your subtheme's .info file include the following line.

  1. scripts[] = js/menu-scroll.js

We are almost there.

Step 3: Define the style for "fixed" class in your theme.

Since we use Omega4, so we will add the following code in our .scss file.

  1. .fixed {
  2. position: fixed;
  3. top:0; left:0;
  4. z-index:1000;
  5. width: 100%;
  6. }

Demo: Sparxsys Solutions