javascriptscroll

I have a problem with a javascript on scroll


I am trying to make a picture stay on top of the site when its first loaded in the middle of the site change it and in the end of the site make it reapear but to be responsive and not like in the code below that i made but im stuck and i dont know how to link it to a top and bottom section of the site to make it work on any resolution of screen. Thank you.

$(function () {
  $(window).scroll(function () {
    if ($(this).scrollTop() > 1000) {
      $(".navbar-brand img").attr("src", "img/logo_big2.png");
    }
    if ($(this).scrollTop() < 1000) {
      $(".navbar-brand img").attr("src", "img/logo_big.png");
    }
    if ($(this).scrollTop() > 4600) {
      $(".navbar-brand img").attr("src", "img/logo_big3.png");
    }
  });
});

I tried putting id-s but since im not that good at that it doesnt work


Solution

  • You can use jQuery to calculate the positions of these sections dynamically:

    Ensure your HTML has identifiable sections:

    <body>
      <div id="top-section"></div>
      <div id="middle-section"></div>
      <div id="bottom-section"></div>
    </body>
    

    jQuery:

    $(function () {
      $(window).scroll(function () {
      var scrollTop = $(this).scrollTop();
    
      // Get the offsets for each section
      var topSectionOffset = $('#top-section').offset().top;
      var middleSectionOffset = $('#middle-section').offset().top;
      var bottomSectionOffset = $('#bottom-section').offset().top;
    
      if (scrollTop >= topSectionOffset && scrollTop < middleSectionOffset) {
       $(".navbar-brand img").attr("src", "img/logo_big.png");
      } else if (scrollTop >= middleSectionOffset && scrollTop < bottomSectionOffset) {
       $(".navbar-brand img").attr("src", "img/logo_big2.png");
      } else if (scrollTop >= bottomSectionOffset) {
        $(".navbar-brand img").attr("src", "img/logo_big3.png");
      }
      });
    });