Add an ID to Header when users scroll over a specific section

#1. First, find ID of Specific Section.

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

#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="6613ff16f9286224504f4218"]');
    const header = $('#header');
    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('add-new');
        return false; 
      }
    });
    if (!isInAnySection) {
      header.removeClass('add-new');
    }
  });
});
</script>

#3. Result

#4. Remember to change ID in the code.

1 Like