0

I am triggering a navigation by clicking a toggle for it. This toggle adds a class "active" on the nav element, to show or hide it. To animate it, the nav element has some styles per default, a transition statement and some opposing styles via the class "active".

To prevent transition problems with display:none/block, I first toggle this property, then add/remove the class.

The weird thing now:

To actually see the transition, I need to set up a delay after toggling the display property. But: this delay can also be 0.

Does anyone know why this delay is needed, if it can actually be zero?

Here's an example (simplified):

CSS:

#nav-main {
  display: none;
  transition: all 2s;
  opacity: 0.0;
}

#nav-main.active {
  opacity: 1.0;
}

JS:

$(function() {

    $("#open").on("click", function(e) {
        e.preventDefault();

        $("#nav-main").show();
        $("#nav-main").addClass("active");
    });

    $("#open-delay").on("click", function(e) {
        e.preventDefault();

        $("#nav-main").show();
        window.setTimeout(function() {
            $("#nav-main").addClass("active");
        }, 0);
    });

    $("#close").on("click", function(e) {
        e.preventDefault();

        $("#nav-main").removeClass("active");
        // here the delay is needed, because we have to wait
        // for the animation to finish, before we hide the element
        window.setTimeout(function() {
            $("#nav-main").hide();
        }, 2000);

    });
});

Working example

https://jsfiddle.net/k9gp3qe2/1/

Thanks for your help

Arne

arnekolja
  • 1,687
  • 5
  • 22
  • 29
  • please check this https://jsfiddle.net/k9gp3qe2/2/ – Karthick Kumar Oct 07 '15 at 15:24
  • 2
    this might be helpful http://stackoverflow.com/a/4575011/1000934 – BenG Oct 07 '15 at 15:24
  • As you are using jQuery, why not use `fadeIn()` and `fadeOut()` for this case? https://jsfiddle.net/k9gp3qe2/3/ – The F Oct 07 '15 at 15:26
  • BG101's link answers my question, I think. As for $.fadeIn(): If it was a simple fade animation, I would try to rely on that. But it is not, the example just spared some more animated styles. Additionally, I prefer CSS animations over JS animations, as they are more performant. Don't know, if jQuery already changed $.fadeIn() to reflect that, but imho I should not use JS where I can use CSS anyway. :-) – arnekolja Oct 07 '15 at 15:32

0 Answers0