Search code examples
javascriptanimationscrollslide

Slide in and out element according to div id scroll position


i am trying to hide and show an element when a div reach the top of the browser. i read few threads and write this code

function hidebtn() {
  var scrollTop = $(window).scrollTop(),
    elementOffset = $('.triger').offset().top,
    distance = (elementOffset - scrollTop);

  var x = document.getElementById("u94");

  if (distance < 1) {
    $(x).animate({'top': '-100px'}, 300);
  } else {
    $(x).animate({'top': '0px'}, 300);
  }
}

window.onscroll = hidebtn

for same reason it doesnt work or if to be more specific it works with a huge delay.

if i change the condition code to

if (distance < 1 ) {
    x.style.display = "none";
} else {
    x.style.display = "block";
}

it works fine but i really like to use the sliding animation

you can see it in JSFIddle

Any suggestions?


Solution

  • Animation function is triggered many times and it will cause some hard to debug issues. A better solution is to use css and some additional checking. This way the hide/show will be triggered only when needed.

    Css

    .hide {
      position: relative;
      transform: translateY(-100%);
      transition: all 0.3s ease-in-out;
    }   
    

    JS

    function hidebtn() {
      var scrollTop = $(window).scrollTop(),
        elementOffset = $('.triger').offset().top,
        distance = (elementOffset - scrollTop);
    
      var x = $("#u94");
        var isHidden = x.hasClass('hide');
    
      if (distance <= 0 && !isHidden) {
        x.addClass('hide');
        console.log("hide");
      } else if (distance > 0 && isHidden) {
        x.removeClass("hide")
      }
    }
    
    window.onscroll = hidebtn
    

    Fiddle: https://jsfiddle.net/andreiTn/yag47gyn/