Arj
Arj

Reputation: 2046

Triggering and looping a CSS3 animation using JavaScript

I am trying to implement a loading animation on an input element. I want the animation to be triggered when the search button on the page has been clicked, and stop when the search has returned (in the callback).

As I'm using AngularJS, currently this is set up as an $http.get call and associated .success callback, so I already have the perfect places in which to add the triggering and the stopping.

Looking at my CodePen example you should be able to see what I am trying to do. The animation should run like this:

In my example I have used :hover to trigger the animation, but eventually this should trigger from JavaScript.

How do I start and end the animation cycle in JavaScript, and how do I make it loop indefinitely until stopped?

[Credit]

http://bradsknutson.com/blog/css-sliding-underline

Upvotes: 0

Views: 83

Answers (2)

Velko Georgiev
Velko Georgiev

Reputation: 694

You can make an animation and then toggle the class:

HTML

<div class="sliding-u-l-r-l" id="inputElement">
  <input type="text" spellcheck="false" placeholder="Hover over me to demo">
</div>

<input type="button" id="start" value="Start" />
<input type="button" id="stop" value="Stop" />

CSS

.sliding-u-l-r-l {
    display: inline-block;
    position: relative;
    padding-bottom: 2px;
}
.sliding-u-l-r-l.animate:before {
    content: '';
    display: block;
    position: absolute;
    height: 2px;
    width: 0;
    bottom: 0;
    background: #4ad;
    animation: animation 1.5s infinite;
}

@keyframes animation {
  0% {
    left: 0;
    width: 0;
  }  

  50% {
    width: 100%;
    left: 0%;
  }

  100% {
    left: 100%;
    width: 0%;
  }
}

JS

$("#start").on("click", function() {
  $("#inputElement").addClass("animate");
});

$("#stop").on("click", function() {
  $("#inputElement").removeClass("animate");
});

If you wont, you can alternate the animation as well (pretty cool effect) just change:

animation: animation 1.5s infinite;

to

animation: animation 1.5s infinite alternate;

Code pen result http://codepen.io/anon/pen/qOQBox

Upvotes: 1

Leonid Lazaryev
Leonid Lazaryev

Reputation: 326

Why don't you want just build a keyframe with animation? Just add infinite to animation iteration count and you are ready...

@keyframes slideAnimation {
  0%:{
    width: 0;
    background: transparent;
    }
  100%:{
    width: 100%;
    background: #4ad;}
}
input.animate {
  animation: slideAnimation 800ms ease infinite normal 0ms running;
}

Then just toggle classes of your input.

Upvotes: 1

Related Questions