What's the best way to add a delay and transition of overlay DIV being shown?

613 Views Asked by At

I'm not really any good at JS, so please bear with me.

I've got this portion of code that makes an overlay appear over the site when the menu is hovered over.

$('#menu-main-menu > .menu-parent-item').hover(
    // when hovered
        function() {
            $('#overlay').css('display','block');
        },
    // when NOT hovered
        function() {
            $('#overlay').css('display','none');
        }
);

The overlay div is shown instantly when the mouse hovers over the menu. The menu items themselves have a nice CSS fade as they come in, but I'd like to apply either a smooth transition, or a delay to the overlay div.

Can something like be easily added to this code, or would that be better being performed by CSS transition also?

2

There are 2 best solutions below

8
On

Use fadeIn/fadeOut with duration like

$('#menu-main-menu > .menu-parent-item').hover(
    // when hovered
        function() {
            $('#overlay').fadeIn(1000);
        },
    // when NOT hovered
        function() {
            $('#overlay').fadeOut(1000);
        }
);

Alternately, you can use show/hide with duration to maintain display:block/none

$('#menu-main-menu > .menu-parent-item').hover(
    // when hovered
        function() {
            $('#overlay').show(1000);
        },
    // when NOT hovered
        function() {
            $('#overlay').hide(1000);
        }
);
1
On

The setTimeOut should allow the delay

setTimeout(
  function() 
  {
    //your code 
  }, 5000);