(Squarespace) Add an ID to Body when users scroll to specific section

#1. First, find Section ID.

In my example, it is: section[data-section-id=“67af02bba487b57f351c879b”]

#2. Next, use this code to Code Injection > Footer

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $(window).scroll(function() {
    const targetSections = $('section[data-section-id="67af02bba487b57f351c879b"]');
    const header = $('body');
    const scrollPosition = $(window).scrollTop();
    const headerHeight = header.outerHeight();
    let isInAnySection = false;
    targetSections.each(function() {
      const section = $(this);
      const sectionTop = section.offset().top;
      const sectionBottom = sectionTop + section.outerHeight();
      if (scrollPosition >= sectionTop - headerHeight && scrollPosition <= sectionBottom) {
        isInAnySection = true;
        header.addClass('white-black');
        return false; 
      }
    });
    if (!isInAnySection) {
      header.removeClass('white-black');
    }
  });
});
</script>

Remember to change Section ID + desired ID you want to add.

#3. Result

1 Like