joa joa - 5 months ago 10
CSS Question

css animations to be applied on click

I am trying to apply CSS animations to my HTML. I have the below code:

HTML:

<button>Save</button>


CSS:

button{
width:100px;
height:40px;
background-color:yellow;
border-radius:10px;
-webkit-animation-name: example;
-webkit-animation-duration: 2s;
-webkit-animation-iteration-count: 3;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: infinite;
}

@-webkit-keyframes example {
0% {background-color:yellow;}
50% {background-color:green;}
}


I am able to get the button change color. But I want it to change color on click. How do I achieve this?

DRD DRD
Answer

For pure CSS solution, use label and input[type = "checkbox"] combination. (code pen: http://codepen.io/anon/pen/dXXXww).

HTML:

<input type = "checkbox" id = "buttonState" class = "btn-state" />
<label for = "buttonState" class = "btn">
  Save
</label>

CSS (LESS):

.btn {
  box-sizing: border-box;
  display: inline-block;
  font: normal 20px/40px Sans-serif;
  text-align: center;
  width: 100px;
  height: 40px;
  background-color: yellow;
  border-radius: 10px;
  cursor: pointer;
}

.btn-state {
  display: none;
  &:checked + .btn {
    animation: example 4s infinite;
  }
}

@keyframes example {
  0%   {background-color: yellow;}
  50%  {background-color: green;}
}

For a JavaScript solution, use the code below. (code pen: http://codepen.io/anon/pen/OXXXqP).

HTML:

<button class = "btn">
  Save
</button>

CSS:

.btn {
  box-sizing: border-box;
  display: inline-block;
  font: normal 20px/40px Sans-serif;
  text-align: center;
  width: 100px;
  height: 40px;
  background-color: yellow;
  border-radius: 10px;
  cursor: pointer;
  outline: 0;
}

.btn.animate {
  animation: example 4s infinite;
}

@keyframes example {
  0%   {background-color: yellow;}
  50%  {background-color: green;}
}

JS:

var $ = document.querySelectorAll.bind(document);
$('.btn')[0].addEventListener('click', function(evt) {
  evt.target.classList.toggle('animate');
});
Comments