Home > Software engineering >  How to show an element on scroll down with javascript?
How to show an element on scroll down with javascript?

Time:10-23

I am wanting to show a button on my website when a user scrolls down on their mobile by 200px. But, I don't want the button to disappear when they scroll back to the top...it stays their until they refresh or navigate to another webpage.

I have the following at the moment which makes the button disappear when the user scrolls back up. How do i amend the code so the button does not disappear on scrolling up?

Note - I am using Wordpress. The below Javascript is in a HTML block and the CSS is within the Custom CSS for the button.

        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    var offset = 200
    $(window).on('load scroll', function(){
        
        if( $(window).scrollTop() > offset ){
            $('body').addClass('show')
        }else{
            $('body').removeClass('show')
        }
    })
    </script>
selector{
    opacity: 0;
    transition: all 0.3s ease-in-out;
}
body.show selector{
    opacity: 1;
}

CodePudding user response:

You are adding the .show class whenever the scroll is past the offset and then you are removing it when it isn't. It should be enough just to remove the else clause.

var offset = 200;
$(window).on("load scroll", function () {
  if ($(window).scrollTop() > offset) {
    $("body").addClass("show");
  }
});
  • Related