0

I created a simple example here: https://codepen.io/marekKnows_com/pen/LaRPZv

What I would like to do is display the red box 2 seconds AFTER the mouse hovers over the blue box. When the mouse leaves the blue box, I want the red box to disappear immediately.

the HTML code looks like this:

<div id="blueBox">
</div>
<div id="redBox" class="">
</div>

The CSS code:

#blueBox {
  background-color: blue;
  width: 200px;
  height: 50px;
}
#redBox {
  display: none;
  background-color: red;
  width: 200px;
  height: 50px;
  transition: display 0s step-end 2s;
}
#redBox.isVisible {
  transition: display 0s step-end 0s;
  display: block;
}

and the JS code:

const el = document.getElementById( 'blueBox' );
const redEl = document.getElementById( 'redBox' );

el.addEventListener( 'mouseover', () => {
  redBox.classList.add( 'isVisible' );
});

el.addEventListener( 'mouseout', () => {
  redBox.classList.remove( 'isVisible' );
});

What I'm seeing is the red box doesn't wait the 2 seconds before making the redbox appear. Why?

Marek Krzeminski
  • 1,308
  • 3
  • 15
  • 40

1 Answers1

1

Use visiblity property for this as you cannot do transition with display property.

Neelam
  • 174
  • 7
  • thank you all! I switched to using opacity and now I have it working as expected. – Marek Krzeminski Mar 04 '19 at 15:57
  • You can not with `visibility` alone as well. – Anurag Srivastava Mar 04 '19 at 15:58
  • @AnuragSrivastava We can do that with visibility. Try out above example with below css. (Note: You have to remove transition property from #redBox.isVisible as it is not required here. It is only required to be set in #redBox):```#blueBox { background-color: blue; width: 200px; height: 50px; } #redBox { visibility: hidden; background-color: red; width: 200px; height: 50px; transition: visibility 0s step-end 2s; } #redBox.isVisible { visibility: visible; }``` – Neelam Mar 04 '19 at 16:06
  • I guess I meant a smooth visual transition instead of show/hide. – Anurag Srivastava Mar 04 '19 at 16:10