aimorris
aimorris

Reputation: 456

How to start animation on click

I have a button on my page, with the label "Dark Theme". I would like to make it so this button changes the effect of the background. When you click it I want it to have the rainbow effect, and when you click it again I want it to go back to the dark theme. I have attached the relevant code for this:

body {
  margin: 0px;
  padding: 0px;
  overflow-y: scroll;
  font-family: Helvetica;
  font-size: 18px;
  background-color: #bdbdbd;
  background-color: #45CEEF;
  -webkit-animation: pulse 1s infinite alternate;
}

h3 {
  font-weight: bold;
  text-decoration: underline;
}
h2 {
  font-weight: bold;
  text-decoration: underline;
}

/*Light Switch*/

label {
  display: block;
  height: 25px;
  width: 100px;
  background: white;
  text-align: center;
  font: 14px/25px Helvetica, Arial, sans-serif;
  margin: 20px 0;
  position: absolute;
  color: black;
  transition: background 0.2s ease-out, color 0.2s ease-out;
}
label:hover {
  background-color: #099;
  color: white;
  cursor: pointer;
  transition: background-color 0.1s ease-in, color 0.1s ease-in;
}
input#lightswitch {
  position: fixed;
  top: -9999px;
  left: -9999px;
}
input#lightswitch + .content {
  color: black;
  transition: background-color 0.5s ease-out, color 0.5s ease-out;
}
/*Switched Off*/

input#lightswitch:checked + .content {
  background-color: #222;
  color: #D3D3D3;
  transition: background-color 0.5s ease-in, color 0.5s ease-in;
}
@-webkit-keyframes pulse {
  0% {
    background-color: #45CEEF;
  }
  25% {
    background-color: #FFF5A5;
  }
  50% {
    background-color: #FFD4DA;
  }
  75% {
    background-color: #99D2E4;
  }
  100% {
    background-color: #D8CAB4;
  }
}
<link rel="stylesheet" type="text/css" href="bda.css">

<body class="body">
  <label for="lightswitch">Dark Theme</label>
  <input type="checkbox" id="lightswitch" />
</body>

My code: https://jsfiddle.net/em07jce9/1/

Upvotes: 1

Views: 118

Answers (1)

Jeriko
Jeriko

Reputation: 6637

When the button is clicked, use Javascript to add a CSS class to the element you want to animate. In your stylesheet, attach the animation to that specific class.

CSS:

.body.animated {
  -webkit-animation: pulse 1s infinite alternate;
}

JS:

$(function() {
  $('button').on('click', function() {
    $('.body').addClass('animated');
  });
});

If you are using a checkbox as the toggle, use the change event:

$(function() {
  $('input#lightswitch').on('change', function() {
    $('.body').toggleClass('animated');
  });
});

Upvotes: 3

Related Questions