Keeping a sliding menu open on mouseover

4.7k views Asked by At

I'm trying to convert an existing menu system which is loaded with inline Javascript into new, more efficient, code using only jQuery.

I have a horizontal bar with rollover images. I have a hidden field in the page containing an integer value. When a page is loaded, the corresponding menu is loaded with a "sticky" version of the image and all other menu items swap images on mouse enter & leave. It was loaded with tons of inline Javascript and a monster Javascript file that was tedious to convert every time I created a new site.

I successfully converted this all to jQuery where I was also able to disable the click on the sticky menu item. Now I can simply set some variables and easily customize it per each site's design.

Working great...

Now comes a new issue. One design contains a bunch of sliding drawers under each menu image. The sliding animations are handled by an external JS file and the menu drawers themselves are each just a DIV containing the content nested inside a container DIV.

So then I wrote some simple stuff for jQuery that animates the DIV and slides it in and out on mouse hover for the menu images.

The problem is that I cannot seem to solve the problem of the mouse moving away from the menu image and down into the menu drawer without the drawer closing. I understand the "why?"... I am leaving the image which triggers the animation to close the drawer before I can get inside. If I apply the hover animations to the drawer container it simply creates a zone under the menu which also triggers the animation, and I don't want that either. It seems to be turning into a more complex problem with jQuery. All this was working fine with the inline Javascript... you could just move your mouse from the image into the adjacent open drawer without triggering the function to close it... as if the inline "mouse enter" for the drawer cancelled out the image's "mouse leave".

Any suggestions?

Thank-you!


EDIT:

I believe I solved this by using .stop(true, false) when passing from the image and into the drawer. This stops the animation dead before it even starts. Then the same when entering the image BEFORE initiating the normal animation... this has the effect of stopping the animation triggered by leaving the drawer and entering the image but also does nothing when just entering the image normally. More testing and then I'll post some sample code.


EDIT #2:

I have it working with "stop()" and "delay()" to control the animation but it's possible to freeze the opening of the drawer if you can get your mouse into it faster than it takes to open it. Installed with 150 ms. but right now set to 300 ms to exaggerate the problem.

Relevant code posted here...

jsfiddle.net/qPLVp/8/


EDIT #3:

Thanks to Neil, this is functioning very well now. With a quicker animation speed, the condition of a mouse overshooting the menu image and entering the drawer will be kept to a minimum. But if it happens to occur, the drawer will not close which is much better than it closing from under your mouse.

http://jsfiddle.net/elusien/PayFw/8/


EDIT #4:

Again thanks to Neil, this is a more efficient version of the same code...

http://jsfiddle.net/PayFw/9/

5

There are 5 answers

11
Neil On BEST ANSWER

I've modified your jsFiddle code to make it work. Basically I have attached a data object to your #menu element. When you are opening this drawer the object is {opening: true}. When the drawer is fully open (animation completed) the object is {opening: false}. I check this when you enter the drawer and if it is false, I stop the animation. If it is true I do NOT stop the animation.

The code is:

    function enter(event) { // mouseenter IMG
        // removed image rollover code

        $('#menu').data({opening: true}).stop(true, false).animate({
            top: '0',
            opacity: 1
        },{
            duration: 300  // slow the opening of the drawer
        },
        function(){$(this).data({opening: false});}
        );
    };
    function leave(event) { // mouseout IMG
        // removed image rollover code

        $('#menu').delay(400).animate({
            top: '-'+$ht+'px',
            opacity: 0
        },{
            duration: 600
        });
    };

    $('#menu').hover(
        function (){ // mouseenter Menu drawer
            if (!$(this).data('opening')) {
                $(this).stop(true, false);
            }
        },
        function (){ // mouseout Menu drawer
            $(this).delay(400).animate({
                top: '-'+$ht+'px',
                opacity: 0
            },{
                duration: 600    
            });

       }
   );

This now works fine. You might want to redo some of your "delay"s in light of this.

1
Brian Driscoll On

It seems like you're looking for the .delegate() function, which attaches a handler to a DOM event now or in the future:

$(".menuItem").delegate(".subMenu","hover", function(){ $(this).show(); });

You can read more about the .delegate() function and its buddy .live() here: http://api.jquery.com/delegate/

8
Neil On

Without seeing the code it is difficult to know if the following would work:

hover() takes as its arguments 2 functions, the first is executed when you enter the image, the second; when you leave the image.

You have presumably set the second function to hide (close) the drawer. I would add a small delay (e.g. delay(100)) before the hide() and set a hover event on the drawer itself to (in the first function argument) stop the animation queue stop(true, true) - this will stop the drawer being closed, and in the second function - close the drawer when you exit it.

2
Neil On

Sparky,

I've come up with a different way of doing things. Basically putting a transparent mask over the "button" and "description" and using a "mouseleave" event on this.

HTML:

<body>
<div id="Container" class="menuContainer" style="position: relative">
<div id="menumask">&nbsp;</div>
<!-- this simulates the menu rollover image -->
<div id="menuitem" style="position:absolute; background-color:#ff00ff; top:10px; width:200px; height:50px; text-align:center;">
    <b>MENU ITEM</b>
</div>

<!-- this is the drawer -->
    <div id="menu" class="menuContent">
        <br/>
        <p>Content of the menu drawer.</p>
        <br/>
        <p>Bla bla bla </p>
        <br/>
        <p>Bla bla bla Bla.</p>
        <br/>
        <p>Bla bla bla Bla bla.</p>
        <br/>
        <p>Bla bla bla Bla bla bla Bla bla.</p>
    </div>

Javascript:

$(document).ready(function() {
    $('#menuitem').bind('mouseenter', enter);
    $('#menumask').bind('mouseleave', leave);

    $('#menu').css({
        height: '500px',
        position: 'absolute',
        paddingTop: '50px',
        width: '200px',
        backgroundColor: '#080',
        zIndex: -1
    }).hide();
    $('#menumask').css({
        height: '550px',
        width: '200px',
        opacity: 0.99,
        position: 'absolute',
        fontSize: '20000px',
        overflow: 'hidden',
        zIndex: 2
    }).hide();

    function enter(){
        $('#menumask').show();
        $('#menu').stop(true,true).animate({height: 500}, 'slow');
    };
    function leave(){
        $('#menumask').hide();
        $('#menu').stop(true,true).slideUp({height:   0}, 'slow');};  
});

You could use this as the basis for your menu system.

Regards Neil

0
lukelliot On

Hey I stumbled on this post while trying to accomplish the same thing. Thought I might leave my solution because it's now 2017, .delegate was deprecated, and using data to keep track of whether or not a transition was still in effect seemed messy.

The key was using the element passed into the mouseleave callback to get the element.relatedTarget.

$('.myMouseoverElements').on('mouseover', function() {        

  activeElements = $('.elements.to.open')
  activeElements.addClass('open')

  activeElements.on('mouseleave', function(element) {

    var sustainElements = $('.elements.to.sustain.mouseover')
    var drawerShouldClose = !$(element.relatedTarget).is(sustainElements)

    if (drawerShouldClose) {
      activeElements.removeClass("open")
      activeElements.off("mouseleave")
    }
  })
})

Thanks for the help!