Let’s Change the Background Color on Scroll in Squarespace

Scroll Down

UPDATE:
I’ve released a plugin that makes this super simple.

Demo Here
Purchase Here


Tutorial Request Time!

I was just wondering if you knew if it was possible to change the background color on scroll in squarespace? Something like this:

https://medium.com/@_patrickcameron/a-complete-beginner-s-guide-to-changing-background-colour-on-scroll-using-jquery-fce686d55049

- Louis

Great idea Louis.

So the general idea here is that we’ll want to change the opacity property of a section’s background color on scroll. And since we’re talking about Sections, we’re talking about Squarespace 7.1—sorry 7.0 folks :(

Since the opacity property will need to change dynamically, we’ll need to use a CSS root variable that we’ll update using javascript. But I’d rather use jQuery, a simpler version of javascript for front-end development, so we’re going to use that.

Instead of walking you through every little step I took. I thought I’d just show my code here and let you ask the questions. Try to read through the code below and understand what exactly is going on. This is the best way to learn how to customize and create awesome stuff on your own.

This is page, not a blog post, so I can’t turn on comments, but shoot me a message.


The Code

STEP 1: ADD JAVASCRIPT
Paste this in the PAGE Settings » Advanced » Page Header Code Injection. Replace the "REPLACE ME" text with the data-section-id of the section you want to change.

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script>   
  $(function(){
    let section = $('[data-section-id="REPLACE ME"]');   
    let sectionHeight = $(section).outerHeight();      document.documentElement.style.setProperty('--section-height', sectionHeight);

    window.addEventListener("scroll", function (event) {
      var scroll = this.scrollY;
      if (sectionHeight > scroll){
        document.documentElement.style.setProperty('--scroll-height', scroll);
      }
    });

    window.addEventListener("resize", function (event) {
      let sectionHeight = $(section).outerHeight();
      document.documentElement.style.setProperty('--section-height', sectionHeight);
    });
  });
</script>

STEP 2: ADD BASE CSS ONCE
This is called a CSS Mixin, you only need to paste it into your Design » Custom CSS area once, and you can call it for each section you want to apply it to in step 3.

.wm-change(@color-start, @color-end){ .section-background{ background-color:@color-end !important; } .section-background:after{ content:""; position:absolute; height:100%; width:100%; background-color:@color-start; opacity:~'calc(1 - (var(--scroll-height)/ var(--section-height) ))'; } }

STEP 3: ADD CSS FOR EACH SECTION
But you’ll need to change the data-section-id and the colors.

[data-section-id="REPLACE ME"]{ .wm-change(teal, transparent); }