Search code examples
javascriptjquerysticky

How to change sticky element depending on scrolling through several section on JS/jQuery?


I need to change the sticky image (by changing class or changing URL attr) while scrolling past several text sections. Asana on their home page has an exact example

check the gif animation here

In front of text section 1 - image 1, while we scroll near text section 2 - image changes to 2nd, and so on. When scrolling back to the top, the same logic, each image appear in front of it's text section.

If there would be only 1 breakpoint, I used code like this:

$(window).scroll(function () {
    if ($(window).scrollTop() >= offset) {
        $(".image").addClass("active");
    } else {
       $(".image").removeClass("active");
    }
});

But since there could be much more sections I need another solution.

Any ideas? Thanks in advance.


Solution

  • Maybe for somebody, it will be helpful, so I will post my solution. Thanks to Alex, I changed logic: I left only one image and on scroll, I change src attr.

    $(window).scroll(function () {
       let index, txtPosition, imgPosition;
    
       $('.text-item').each(function () {
          index = $(this).index();
          txtPosition = $(this).offset().top;
          imgPosition = $('.image-item').offset().top + 50;
    
          if (txtPosition < imgPosition) {
             $('.image-item img').attr('src', $(this).attr('data-image'));
          }
    
       });
    
    });