Home > Mobile >  trigger CSS animations onlcick
trigger CSS animations onlcick

Time:08-08

I have created an animation for an element on my page and it always runs when the page is refreshed but i would like the animation to play when an element is clicked. How would i go about doing this?

CSS:

#login-or-signup-selection {
    display: flex;
    animation-name: test;
    animation-duration: 5s;
    position: relative;
    height: 70%;
}

@keyframes test {
    0% {top: 0px;}
    50% {top:300px}
    100% {top: 0;}
}

HTML:

<p id="clickMe">Element to click</p>

CodePudding user response:

$('#clickMe').click(function () { 
  $(this).addClass('login-or-signup-selection');
  $(this).on("animationend", function(event) {
    $(this).removeClass('login-or-signup-selection')
  });
});
.login-or-signup-selection {
    display: flex;
    animation-name: test;
    animation-duration: 5s;
    position: relative;
    height: 70%;
}

@keyframes test {
    0% {top: 0px;}
    50% {top:300px}
    100% {top: 0;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="clickMe">Element to click</p>

CodePudding user response:

You would need some JavaScript for this.

First off, separate the CSS animation properties, and anything else related to your animation, and add them to their own class.

Next up, the JavaScript. You'll want to add an event listener to your element to add the animation class when clicked.

const yourElement = document.getElementById('clickMe');
yourElement.addEventListener('click', function() { this.classList.add('animation-class'); });
#clickMe {
    display: flex;
    position: relative;
    height: 70%;
}

.animation-class {
  animation-name: test;
  animation-duration: 5s;
}

@keyframes test {
    0% {top: 0px;}
    50% {top:300px}
    100% {top: 0;}
}
<p id="clickMe">Element to click</p>

CodePudding user response:

If you want only css and don't even care about js onclick events for now,

use the :active pseudo selector.

The only downside is that it only plays while (=during) e.g. the mouse button is down.

  • Related