DN. DN. - 1 year ago 69
CSS Question

Remove stickiness after scrolling element

It is pretty simple to make some element sticky after scrolling several pixels. However, how would you do an opposite of that?

I want an element to be sticky, but after scrolling e.g. 400px (to its original position) it would remain there.

A very good example can be found here http://ultrahd-3d-televize.heureka.cz

enter image description here

Answer Source

It took a while for me to write my answer, because I used the opportunity to learn about debouncing, to prevent that the piece of code that checks on scroll gets called every time one scroll is done (in theory flooding your browser).


My jQuery:

var menuHeight = $('.menu').height();

var scrollingMachine = debounce(function() {
  var $this = $(this);

  if($(document).scrollTop() > (menuHeight - 850)) {
        console.log($(document).scrollTop() - 850);
    else {
}, 100);

window.addEventListener('scroll', scrollingMachine);

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    var callNow = immediate && !timeout;
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);

Debouncing helps by only calling the function after the scrolling stops, with a maximum of once every 100ms. (just change the 100 to something else if you want it to react faster).

It's a good idea to debounce all functions that get triggered on scroll or for example resizing, to prevent the browser from calculating for every pixel scrolled or resized and only firing when the user is done scrolling or resizing. It can also be used in the case of typing or AJAX calls. Especially in the case of AJAX calls, you want to only fire a function when necessary, not whenever the user lifts his finger from a letter. See an example here.