Nathan
Nathan

Reputation: 1540

What's the robust way to have JS callbacks wait on a CSS3 transition, iff the transition happens?

In the past with JS transitions, one could specify some behavior to happen after the transition, via a callback. E.g.

//jQuery
function hideTheContent() {
    $('#content').fadeOut(1000,function() {
      mandatoryLogicAfterHidingContent();
    });
}

Now with CSS3 transitions, we can do something like this.

//CSS
#content {
  opacity:1;
  transition: opacity 1s;
}

.hidden {
  opacity:0;
  transition: opacity 1s;
}

//jQuery
function hideTheContent() {
    $('#content').addClass('hidden');
    // still need to run mandatoryLogicAfterHidingContent
}

I know of the new transitionend events, so hypothetically we could do something like this:

//jQuery
function hideTheContent() {
    $('#content').on('transitionend', function(e) {
      mandatoryLogicAfterHidingContent()
    })

    $('#content').addClass('hidden');
}

but since we're now separating out the JS from the UI, it's possible that someone else could come along with a new UI where content-hiding is instant, remove the CSS3 transition, and inadvertently break the JS call to mandatoryLogicAfterHidingContent().

Another scenario, say I have a box and there's a reset function that resizes said box to size 50x50 (with transition), then calls a mandatoryLogicAfterResize(). If I call the reset fn twice, I don't think the transition event is guaranteed to fire in this case - but I still need mandatoryLogicAfterResize to run both times.

In more complex codebases, I also worry about other transitions getting called before the specific transition I'm targeting. and prematurely triggering the mandatoryLogic(). I guess the core problem here is, with CSS3 transitions, how can I defensively tie the mandatoryLogicAfterHidingContent() event handler with my and only my invocation of addClass('hidden'), like I could with the jQuery callback?

Upvotes: 2

Views: 29

Answers (0)

Related Questions