Reputation: 22480
I want a CSS3 transition to start after click.
Now it works fine if the element gets added a class with jQuery (see span.toggle-nav.two
) which knows then what to do.
I've tried with :focus
(see span.toggle-nav.one
) but that doesn't work. How can I make it work without jQuery?
Please have a look here: http://jsfiddle.net/aE4C7/ clicking on Two
works but clicking on One
does not.
<span class="toggle-nav one">One</span>
<span class="toggle-nav two">Two</span>
<script type="text/javascript">
$('.toggle-nav.two').on('click',function(){
$(this).addClass("click");
});
</script>
<style type="text/css">
.toggle-nav {
background-image:url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS8hRiDDs6RJRzelpuFRX2wG5Wx2cQPOBWKYCOmlA2Wr34dx1vv);
background-repeat:no-repeat;
width:50px;height:50px;
display:inline-block;
}
.toggle-nav.one:focus {
-webkit-animation: spin 0.6s infinite linear;
-moz-animation: spin 0.6s infinite linear;
-o-animation: spin 0.6s infinite linear;
-ms-animation: spin 0.6s infinite linear;
}
.toggle-nav.two.click {
-webkit-animation: spin 0.6s infinite linear;
-moz-animation: spin 0.6s infinite linear;
-o-animation: spin 0.6s infinite linear;
-ms-animation: spin 0.6s infinite linear;
}
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg);}
100% { -webkit-transform: rotate(180deg);}
}
@-moz-keyframes spin {
0% { -moz-transform: rotate(0deg);}
100% { -moz-transform: rotate(180deg);}
}
@-o-keyframes spin {
0% { -o-transform: rotate(0deg);}
100% { -o-transform: rotate(180deg);}
}
@-ms-keyframes spin {
0% { -ms-transform: rotate(0deg);}
100% { -ms-transform: rotate(180deg);}
}
</style>
Is there a way to make this work without jQuery?
Upvotes: 1
Views: 399
Reputation: 71140
You can actually do this using purely CSS - The only way to correctly simulate click events in CSS is to fake it with a checkbox, otherwise using :active
or :focus
will stop any applied transition or animation as soon as the element loses focus, not when it is clicked on again.
HTML
<div>
<input id='box' type='checkbox' />
<label for='box'>Click Me!</label>
</div>
CSS
div {
position:relative;
}
label {
position:absolute;
left:0;
background:white;
}
input[type=checkbox] {
opacity:0;
}
input[type=checkbox]:checked + label {
-webkit-animation: spin 0.6s infinite linear;
-moz-animation: spin 0.6s infinite linear;
-o-animation: spin 0.6s infinite linear;
-ms-animation: spin 0.6s infinite linear;
}
@-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(180deg);
}
}
@-moz-keyframes spin {
0% {
-moz-transform: rotate(0deg);
}
100% {
-moz-transform: rotate(180deg);
}
}
@-o-keyframes spin {
0% {
-o-transform: rotate(0deg);
}
100% {
-o-transform: rotate(180deg);
}
}
@-ms-keyframes spin {
0% {
-ms-transform: rotate(0deg);
}
100% {
-ms-transform: rotate(180deg);
}
}
Upvotes: 1