← Snippets - Script

Sticky Item with Class Added

For a lot of sticky/fixed items, we can simply put position: sticky on it nowadays. That allows it to appear position: relative first, and then it only becomes fixed when it hits the top of the window. However, position: sticky only works on its own if the item stays exactly the same when it starts to stick. If there is any change like a background color being added, a height change, etc., position: sticky is not enough–you’ll need to also add a class. So here’s how to do that!

Bootstrap 5

How To

banno-functions.js

Add this to the methods section.

scrollEvents: function() {
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
          windowHeight = window.innerHeight,
          bodyHeight = bodyTag.innerHeight,
          headerOffset = hdr.offsetTop,
          headerHeight = hdr.innerHeight;
      if ((scrollTop > headerOffset - 1 && (scrollTop > 0) && (window.innerWidth > 767)) || (top != self)) {
        hdr.classList.add('stuck');
      } else {
        hdr.classList.remove('stuck');
      }
    },

Within the methods section, find the initialize function section and add this line to it:

      this.scrollEvents();

script.js

Find the scroll event listener, which should also contain a piece about the DQM Premium accessibility button. Insert this line, making sure that it doesn’t go within the DQM section.

    banno.methods.scrollEvents(); 

Bootstrap 3/4

In theory, this should probably work on sites of any age, but it’s recent enough that we’ve only really used it for BS3 and BS4 sites.

How To

banno-functions.js

If you already have a scrollevents function in your banno-functions.js, you can just paste in lines 8 - 12 (and obviously the associated variables!)

If you don’t have a scrollevents function, go ahead and use the whole thing! Just make sure to also add banno.site.scrollEvents(); to your banno.site.initialize function at the top.

banno.site.scrollEvents = function () {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
      windowHeight = $(window).height(),
      bodyHeight = $('body').height(),
      headerOffset = $('header').offset().top,
      headerHeight = $('header').height();
  if ((scrollTop > headerOffset - 1 && (scrollTop > 0) && ($(window).width() > 767)) || (top != self)) {
    $("header").addClass("stuck");
  } else {
    $("header").removeClass("stuck");
  }
}

scripts.js

Add this within your large function (or edit your existing “on scroll” function to include the new scrollEvents function.)

$(window).on('scroll', function() { 
	banno.site.scrollEvents(); 
});

Example Sites

Tags: BS3, BS4, BS5, menu, sticky, fixed, js, javascript, script, css, scss, sass