skip to Main Content

I have added a horizonal line after a section using CSS:

.section:after {
  content: "";
  position: absolute;
  bottom: -20px;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #000;
  animation: line-appear 1.5s forwards;
  visibility: hidden;
}

@keyframes line-appear {
  to {
    width: 100%;
    visibility: visible;
  }
}

I also added javascript into the html:

$(document).ready(function() {
  $(window).scroll(function() {
    $(".section").each(function() {
      var position = $(this).offset().top;
      var scrollPosition = $(window).scrollTop() + $(window).height();

      if (scrollPosition > position) {
        $(this).find(".section:after").css("animation-play-state", "running");
      }
    });
  });
});

However, the line animated before I scrolled to it.
Does anyone know how to make the line starts animated just when I scroll to it?

Does anyone know how to make the line starts animated just when I scroll to it?

2

Answers


  1. animation-play-state already has the value running, before your JavaScript code even sets it. (Because that is its initial value, and by using the animation shorthand property in your CSS, you set all the "sub-properties" that you don’t explicitly specify, to their initial default.)

    You need to specify it as paused in the initial state:

    animation: line-appear 1.5s forwards paused;
    
    Login or Signup to reply.
  2. Try this:
    css:

    .section:after {
    content: "";
    position: absolute;
    bottom: -20px;
    left: 0;
    width: 0;
    height: 2px;
    background-color: #000;
    visibility: hidden;
    }
    
    .section.animate-line:after {
     animation: line-appear 1.5s forwards;
    }
    

    JavaScript:

     $(document).ready(function() {
      $(window).scroll(function() {
        $(".section").each(function() {
           var position = $(this).offset().top;
           var scrollPosition = 
       $(window).scrollTop() + $(window).height();
    
           if (scrollPosition > position) {
              $(this).addClass("animate-line");  
                      //Add the animate-line class
                }
         });
         });
         });
    

    Let me know if this can be helpful to you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search