To achieve what you're attempting, a CSS hack would be necessary to simulate a click event.
For more information, refer to CSS Click events
You can also view my solution on JSFiddle
<input type="checkbox" id="toggle-1">
<label for="toggle-1">
<div>Control me</div>
</label>
Below is the CSS code snippet:
/* Checkbox Hack */
input[type=checkbox] {
position: absolute;
top: -9999px;
left: -9999px;
}
label {
display: inline-block;
margin: 60px 0 10px 0;
cursor: pointer;
}
/* Default State */
div {
background: green;
width: 400px; height: 100px;
line-height: 100px;
color: white;
text-align: center;
transition: transform 2s ease;
}
/* Toggled State */
input[type=checkbox]:checked ~ label div {
background: red;
transform: rotate(45deg);
}
The key sections in the CSS are the toggled state
, checkbox hack
, and the transition
property within the default state of the div.
UPDATED ANSWER
If your JavaScript handles click events and toggles classes, consider using animation
instead of transition
. Here's an example based on your description:
Here is the corresponding CSS code:
@keyframes spin-forward {
from {
transform: rotate(0deg);
} to {
transform: rotate(45deg);
}
}
@keyframes spin-backword {
from {
transform: rotate(45deg);
} to {
transform: rotate(0deg);
}
}
.spin-right {
animation: spin-forward 2s ease forwards;
}
.spin-left {
animation: spin-backword 2s ease forwards;
}
And here is the accompanying JavaScript code:
$(function() {
$('div').on('click', function() {
var el = $(this);
var klass = this.className;
if (klass === "") {
el.addClass('spin-right');
} else if (klass === 'spin-right') {
el.attr('class', 'spin-left');
} else {
el.attr('class', 'spin-right');
}
});
});
The advantage of using animation
lies in its enhanced control. The use of forwards
enables an element to remain in the new state post-animation completion.
See the live demonstration on JSFiddle
I hope this resolves your issue.