skip to Main Content

I’m working on a website where I want to enable an element to fade in when i scroll down to a certain point. I’ve tried implementing this using vanilla HTML, CSS, and JavaScript, but the element is not triggering the animation on scroll as expected. I’ve followed various tutorials and suggestions, but I’m still facing difficulties. Could you please help me troubleshoot and provide guidance on how to make a fade-in animation trigger on scroll?

Used code:

<html>
<head>
</head>
<body>
    <h1 class="anim">hi</h1>
</body>
<script>
    const obj = document.getElementById("anim")
    $(window).scroll(function() {
        var height = $(window).scrollTop();
    
        if(height  > 100) {
            $(obj).addClass("fade");
    
        }else{
            $(obj).addClass("fade");
        }
    });

</script>
</html>

2

Answers


  1. There are few issues in your code :

    1. You are targeting the element by ID but you have provided class = "anim" in your html code. Give id = "anim" to the h1 element.
    2. Include necessary libraries cdn in your code i.e. jquery,vanilla,etc.

    I thinks with these changes your code will work fine.

    Login or Signup to reply.
  2. When the page is scrolled, the script calculates the distance of the element from the top of the viewport. If the element is within 100 pixels from the bottom of the viewport, the "fade" class is added, making the element gradually appear with opacity transition.

          $(document).ready(function() {
                const obj = document.getElementById("anim");
                $(window).scroll(function() {
                    var scrollTop = $(window).scrollTop();
                    var elementOffset = $(obj).offset().top;
                    var distance = (elementOffset - scrollTop);
                    
                    if (distance < $(window).height() - 100) {
                        $(obj).addClass("fade");
                    } else {
                        $(obj).removeClass("fade");
                    }
                });
            });
    .anim {
        opacity: 0;
        transition: opacity 1s;
      }
      .fade {
        opacity: 1;
      }
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
       <h1 id="anim" class="anim">hi</h1>
          <h1 id="anim" class="anim">hi</h1>   <h1 id="anim" class="anim">hi</h1>
             <h1 id="anim" class="anim">hi</h1>
                <h1 id="anim" class="anim">hi</h1>
    
        <p>This is some content to create scrollable space...</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search