1

I know that we can use the below css to blink a div for the number of times specified:

html:

<div class="blink">blinking text</div>

css:

@-webkit-keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.0; }
100% { opacity: 1.0; }
}
@-moz-keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.0; }
100% { opacity: 1.0; }
}
.blink {
-webkit-animation: blinker 1s 5;
-moz-animation: blinker 1s 5;
animation: blinker 1s 5;
}

By using the css way, the div will blink after the page loaded without us calling any js function. But then what if i want to re-blink the div after the user press a button? There's no function to call on "onclick".

<button onclick="">BLINK AGAIN!</button>

Any idea how to do it?

JSFIDDLE

Coolguy
  • 2,225
  • 12
  • 54
  • 81
  • You would need to toggle the class. – Paulie_D Oct 27 '15 at 16:24
  • 1
    It's quite tricky. Check this: https://css-tricks.com/restart-css-animation/ – Vlad DX Oct 27 '15 at 16:25
  • The crux of this question is the same as [**this one that I answered yesterday**](http://stackoverflow.com/questions/33347992/reuse-css-animation-in-reversed-direction-by-resetting-the-state/33351228#33351228). You **cannot restart a CSS animation using CSS alone**. – Harry Oct 27 '15 at 16:27

1 Answers1

1

You need to remove the class 'blink' then add it back again, in order to restart the CSS animation

You'll need to use a setTimeout so that it doesn't have the class added to it before it has has the class taken away from it

$("#blinkagain").click(function() {
    var $el = $(".blink");
    $el.removeClass("blink");
    setTimeout(function() {$el.addClass("blink");}, 500);
});
@-webkit-keyframes blinker {
  0% {
    opacity: 1.0;
  }
  50% {
    opacity: 0.0;
  }
  100% {
    opacity: 1.0;
  }
}
@-moz-keyframes blinker {
  0% {
    opacity: 1.0;
  }
  50% {
    opacity: 0.0;
  }
  100% {
    opacity: 1.0;
  }
}
.blink {
  -webkit-animation: blinker 1s 5;
  -moz-animation: blinker 1s 5;
  animation: blinker 1s 5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blink">blinking text</div>
<button id="blinkagain">BLINK AGAIN!</button>
joe_young
  • 4,107
  • 2
  • 27
  • 38