Ujjwal Saxena
Ujjwal Saxena

Reputation: 141

Activate CSS Animation when visible

I am using a CSS animation on my webpage, this animation is in the middle of my page. Its animation starts as soon as I visit the webpage. So the user is not able to see it, I have tried few solutions provided on the internet but none of it seems to work for me.

.pcb-text {
  display: flex;
  justify-content: center;
  align-items: center;
}

.pcb-text p {
  font-size: 35px;
  animation: typing 2s steps(45), 
             blink-caret 0.85s step-end infinite;
  overflow: hidden;
  white-space: nowrap;
  margin: 0 auto;
  border-right: .12em solid orange;
}

@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}


/* The typewriter cursor effect */

@keyframes blink-caret {
  from,
  to {
    border-color: transparent
  }
  50% {
    border-color: orange;
  }
}
<div class="pcb-text" id="animated_text">
    <div class="text-center">
      <p>Some Text Here</p>
    </div>
</div>

I am new to this, so I would really appreciate that if you are giving an answer which includes JS or JQuery, please use a simple method which I can understand

Upvotes: 1

Views: 4312

Answers (1)

PeterSH
PeterSH

Reputation: 475

You could put the animation in a separate class, and add this class when the element is scrolled into view.

This can be done with jQuery by adding a custom function that detects when the element is in view, and trigger this function every time the user scrolls.

// function to detect if an element is scrolled into view
function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
};

// listen for scroll event
$(window).scroll(function () {
  // check if element is scrolled into view
  if (isScrolledIntoView($('#animated_text'))) {
    // element is scrolled into view, add animation class
    $('#animated_text').addClass('animation');
  }
});
.pcb-text {
  display: flex;
  justify-content: center;
  align-items: center;
}

.pcb-text p {
  font-size: 35px;
 
  overflow: hidden;
  white-space: nowrap;
  margin: 0 auto;
  border-right: .12em solid orange;
}

/* move animation to separate class */
.animation p {
  animation: typing 2s steps(45), 
             blink-caret 0.85s step-end infinite;
}

@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}


/* The typewriter cursor effect */

@keyframes blink-caret {
  from,
  to {
    border-color: transparent
  }
  50% {
    border-color: orange;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 1000px"></div>
<div class="pcb-text" id="animated_text">
    <div class="text-center">
      <p>Some Text Here</p>
    </div>
</div>

Upvotes: 1

Related Questions