user6450194
user6450194

Reputation:

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?

Upvotes: 1

Views: 127

Answers (2)

TylerH
TylerH

Reputation: 21087

If you're just trying to change the color of a button on click, CSS transitions are simpler than animations and you can do this without any JavaScript:

#buttonState {
  display:none;
}

#buttonState + label {
    width: 100px;
    height: 40px;
    background-color: yellow;
    border-radius: 10px;
    transition: background-color 4s linear;
}

#buttonState:checked + label {
    transition: background-color 4s linear;
    background-color: green;
}
<input type="checkbox" id="buttonState" class="btn-state" />
<label for="buttonState" class="btn">Save</label>

You can even make this element look like a button with some extra styles.

Upvotes: 2

DRD
DRD

Reputation: 5813

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');
});

Upvotes: 1

Related Questions