Search code examples
csshoverdelay

Delay "unhover" action


#login-panel-ghost {
  display: none;
  transition-delay: 2s;
}
.top-menu-login:hover #login-panel-ghost {
  display: block;
  position: fixed;
  width: 250px;
  height: 180px;
  transition-delay: 2s;
}
<span class="top-menu-login">Login
  <div id="login-panel-ghost">
    <h2>Log in!</h2>
    <form>
      <input type="text" placeholder="Username">
    </form>
  </div>
</span>

Now, let me explain what I would like to accomplish: I've a span .top-menu-login which will be displayed as a phrase, in this case "Login". Furthermore, the div #login-panel-ghost is originally hidden, but when the mouse passes over "Login" the div should appear.

I managed to do that, the problem is that I would like to delay the element disappearing after the mouse unhovers the "Login"!

I've tried this code so far, that I found on Stack Overflow, but I think the fact that the hover changes another div is causing trouble.

P.S. I know it should be easy with JavaScript, but I'd like to try without it!


Solution

  • You are on the right lines using transition-delay: 2s;, however, there are a couple of factors that mean this won't work:

    • You cannot animate display, it is either there (display: block;) or not (display: none;)
    • You are not specifying a transition so there is nothing for transition-delay: 2s; to effect

    To make this work using CSS you can do the following:

    • Add height: 0; to #login-panel-ghost to effectively hide the element
    • Add height: 180px; to .top-menu-login:hover #login-panel-ghost to effectively show the element
    • Transition on the height changing it from 0 to 180px by adding transition: height 0s; to #login-panel-ghost
    • Add overflow: hidden; to allow the content that exceeds the boundries of #login-panel-ghost to be hidden
    • Add transition-delay: 2s; to #login-panel-ghost to delay the transition when .top-menu-login is not hovered over
    • Add transition-delay: 0s; to #.top-menu-login:hover #login-panel-ghost to ensure there is no delay when the user hovers over the element

    #login-panel-ghost {
      height: 0;
      overflow: hidden;
      transition: height 0s;
      transition-delay: 2s;
    }
    .top-menu-login:hover #login-panel-ghost {
      height: 180px;
      position: fixed;
      transition-delay: 0s;
      width: 250px;
    }
    <div class="top-menu-login">Login
      <div id="login-panel-ghost">
        <h2>Log in!</h2>
        <form>
          <input type="text" placeholder="Username" />
        </form>
      </div>
    </div>