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

3
  • You would need to toggle the class. Commented Oct 27, 2015 at 16:24
  • 1
    It's quite tricky. Check this: css-tricks.com/restart-css-animation Commented Oct 27, 2015 at 16:25
  • The crux of this question is the same as this one that I answered yesterday. You cannot restart a CSS animation using CSS alone. Commented Oct 27, 2015 at 16:27

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

It's not working sir..
Sorry, I messed up, have a look now @Coolguy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.