Ohar
Ohar

Reputation: 320

How to compose JS events and CSS transition timings?

Example

  1. Javascript function adds some CSS class to HTML element.
  2. Because of that, HTML element starts to animate its styles (hiding) with transition.
  3. After it hides we want to execute another JS function to add another CSS class to another element and make it visible.

The problem is that functions are JS code, but animations — CSS.

How to use the same time values for JS and CSS code? I want to follow DRY and get only single source of truth.

Is it possible?

Upvotes: 0

Views: 124

Answers (2)

johnyTran
johnyTran

Reputation: 5

jquery solution for timed css transitions and javascript event listener.

.class_one {

  transition:1s

}
.class_two {

  transition:1s;
  transition-delay:1s;
}

//jquery function
 $('button').click(function(){
   $(this).addClass('class-one class-two');
 });

Using transition delay allows you to time when your transitions to take place consecutively.

Upvotes: 0

Andria
Andria

Reputation: 5075

The magic of transitionend

What you're looking for is to use the event listener transitionend after adding the class with .classList.add

element.classList.add('yourTransitionAnimationClass')
element.addEventListener('transitionend', callbackFunction)

Upvotes: 2

Related Questions