Skip to content

Instantly share code, notes, and snippets.

@opi
Last active May 6, 2021 09:04
Show Gist options
  • Save opi/4a6669530d3ec227fbfc697592fbeb69 to your computer and use it in GitHub Desktop.
Save opi/4a6669530d3ec227fbfc697592fbeb69 to your computer and use it in GitHub Desktop.
Drupal : Sticky navigation with debounce

In yourtheme.libraries.yml

global:
  js:
    dist/js/global.js: { minified: true }
  dependencies:
    - core/drupal
    - core/drupal.debounce

In your global.js script

(function(Drupal, debounce) {

  Drupal.stickyNavigation = function(element) {
    const scrollChange = debounce(function() {
      const offset = 1;
      // Get the current scroll position
      var scroll = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
      if(scroll >= offset) {
        element.classList.add('sticky')
      }
      else {
        element.classList.remove('sticky');
      }
    }, 50);
    window.addEventListener('scroll', scrollChange, false);
  };

  Drupal.behaviors.yourtheme = {
    attach: function (context, settings) {

      // Sticky Navigation
      const navigation = document.querySelector('.layout-navigation');
      Drupal.stickyNavigation(navigation);

    }
  };

})(Drupal, Drupal.debounce);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment