Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

123
Views
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.

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

I think this is the pattern you are looking for:

$(window).scroll(function () {
    image1();
    image2();
    image3();
});

function image1() {
    var min = 0;
    var max = 400;
    if(window.scrollY >= min && window.scrollY < max) {
    $("img").attr("src","https://cdn.picpng.com/head/head-the-dummy-avatar-man-tie-72756.png");
  }
}

function image2() {
    var min = 400;
    var max = 800;
    if(window.scrollY >= min && window.scrollY < max) {
    $("img").attr("src","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRlfO4xTPtZVZfQCZqpaoOV4_c3G-OMUJ00IU0fy8wnDOZzud3N2xYnMrzJbXLCs7vlmWM&usqp=CAU");
  }
}

function image3() {
    var min = 800;
    var max = 10000;
    if(window.scrollY >= min && window.scrollY < max) {
    $("img").attr("src","https://www.unite2canada.com/images/dummy-user.png");
  }
}

You can see this piece of code at work right here

7 months ago · Juan Pablo Isaza Report

0

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'));
      }

   });

});
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs