PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to show an element on scroll down with javascript?

 October 24, 2022     css, javascript, jquery, scroll, wordpress     No comments   

Issue

I want 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 there until they refresh or navigate 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 an 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;
}


Solution

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


Answered By - Fralle
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing