Ahri Daniels Ahri Daniels - 1 year ago 39
CSS Question

How to trigger css animation w/ delay on click using javascript/jquery?

so I have a question. I'm trying to start up CSS animation through Javascript/JQuery. The animation is of my navigation menu. It consists of 4 links each placed in a div with the width set to zero. The animation makes the width 100% of the parent's width at a delay for +100ms starting at 300 from top element to bottom so it appears as if the all come out separately to form the menu. Also a method to reverse the animation on click would be great as well. I tried using toggle() but was unsuccessful.

<div class="navbar">
<a href="index.php"><div id="nav1">Home</div></a>
<a href="about.php"><div id="nav2">About</div></a>
<a href="work.php"><div id="nav3">Work</div></a>
<a href="contact.php"><div id="nav4">Msg</div></a>
</div>


Here is the javascript code

function expand() {
var navName = '#nav';
var delay = 0;
for(i = 1; i < 5; i++){
//Resets nav value
navName = '#nav';
delay = 200
//Adds number to class name
navName += i;
delay += 100;
//alert(navName + delay);
$(navName).css('animation', 'expand ease 500ms forwards');
$(navName).css('animation-delay', delay +'ms');


}

Answer Source

Rather than apply the animation property using JQuery, you could apply it by toggling a class. This class would contain the animation properties you need already.

$('.target').on('click', function() {
  $(this).toggleClass('animate');
});
.target {
  padding: 1em;

  background: cornflowerblue;
}

.animate {
    animation: expand 1s linear;
    animation-delay: 200ms;
}

@keyframes expand {
    0% {
        transform: scale(1);
        opacity: 0;
    }
    60% {
        transform: scale(2);
        opacity: 1;
    }
    100% {
        transform: scale(1.5);
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">click me</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download