Search code examples
javascripthtmlcssparallax

How do I make one div scroll slower or faster than other items on the page, using pure CSS or CSS/JS (without JQuery)?


All I want is to do is to make one element on the page (a div is easiest) scroll slower or faster than the other items on the page. For example, when scrolling, this particular div will move at 50% or 200% of the speed of the other items, etc.

It seems like such a simple, straightforward thing, but I can't find any examples of this. Also, I don't want to use JQuery, someone else's sketchy / overly complicated 3rd party plugin, etc. Just simple, clean, CSS and JS.


Solution

  • So I have managed to come up with this which is not too complex, however, it does scroll relative to the users scroll speed, but does work with scroll wheel, scrollbars, and keyboard.

    It also scrolls up and down.

    You can change the speed to suit your needs, but 10 worked for keeping it pretty much in view all the way down for my scroll speed, but left it behind when faster or using Page Down.

    document.addEventListener("DOMContentLoaded", function DomContentLoaded(){
      //Get the element you want to slow down;
      var slowDiv = document.getElementById('slowDiv');
      //Set its style.top to be the offsetTop so if style.top is not set, it will still work.
      slowDiv.style.top = slowDiv.offsetTop + 'px';
      //set the last scrollTop to use for direction
      var lastScrollTop = 0;
      //Get the element you are scrolling against
      var relativeSpeedDiv = document.getElementById('main');
    
    
      var moveLittle = function MoveLittle(speed, scrollY) {
        //Get the current top of the slow element
        var topVal = parseInt(slowDiv.style.top);
        //Check scroll direction
        if (isScrollingDown(scrollY)) {
          topVal = topVal + speed;
        } else {
          topVal = topVal - speed;
        }
        //Set new top of slow element
        slowDiv.style.top = topVal + 'px';
      };
    
      var isScrollingDown = function IsScrollingDown(scrollY) {
        var retVal = false;
        if (scrollY > lastScrollTop) {
          retVal = true;
        }
        lastScrollTop = scrollY;
        return retVal;
      };
    
      window.onscroll = function WindowScroll() {
        //Send speed and current scroll Y
        moveLittle(10, this.scrollY);
      }
    
    });
    .biggestBig {
        margin: auto;
        align-self: center;
        width: 90%;
        min-height: 9999em;
    }
    
    .faded {
        background: linear-gradient(gray, black);
    }
    
    .slow {
        width: 2em;
        height: 2em;
        background-color: #ee9b0b;
        position: absolute;
    }
    <div id="mainDiv" class="biggestBig faded">
        <div id="slowDiv" class="slow"></div>
    </div>