Home > Software design >  Hide div when User is scrolling on mobile / display div when the scroll stops
Hide div when User is scrolling on mobile / display div when the scroll stops

Time:04-27

I didn't find the exact answer to my problem that I will explain here :

I want to hide a fixed element when the user is scrolling. When the scroll action is finished, the div is displayed again. This does not take into account a trigger on the height (with a scrollTop for example) but simply on the scroll action itself.

This behaviour is for mobile use.

I made a quick code snippet for trying something :

thanks a lot

  window.addEventListener('scroll', function() { 
    document.getElementById('paragraph').classList.toggle('test');
  });
p {
  position:fixed;
  background:wheat;
  
}

div {
  height:2000px;
  background-image: linear-gradient(red, yellow);
}
<div>
<p id="paragraph">Has to be hidden on scroll</p>
</div>

CodePudding user response:

When scroll function is triggered we will hide the div and then we have to check whether the scrolling is stopped for this we can use setTimeout function

window.addEventListener("scroll", function () {

  $("#paragraph").fadeOut(); //hide div

  document.getElementById("paragraph").classList.toggle("test");

  clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
     $("#paragraph").fadeIn(); //unhide div after few milliseconds
   }, 550));

});

codepen

CodePudding user response:

Here is a solution i have used in the past:

https://codepen.io/webdevjones/pen/GRybONR

//initialize scrollTimer
let scrollTimer = -1;

//add event listner
window.addEventListener("scroll", () => { 
  //get the element(s) to hide while scrolling
  const elem = document.getElementById('paragraph')
  //hide the element(s), you could also just use opacity 
  //or visibility depending on your use case
  elem.style.display = 'none'
  
  //while we are scrolling, restart the timer
  if (scrollTimer != -1){
        clearTimeout(scrollTimer)
  }
  
  //if the timer isnt cleared, we run the function to 
  //display the element(s) again
  scrollTimer = window.setTimeout(() => {
      elem.style.display = 'block'
  }, 1); 
  //running the function 1ms after scroll stop, 
  //you could increase this number if neccesary
})
  • Related