Question

In a site I am managing, I have this styled link that on click fades in a drop list below it, so that the user can select a genre.

I have the Fade in working perfectly, the issue I am running into is trying to determine whether or not the drop down list was hovered on so that I can hide it if the user hovers off of the styled link without entering the drop down list.

So, the drop down list Fades in, the user doesn't enter the drop downed element, then the element fades out, however, if the user enters the drop downed element (while leaving the clicked linked that trigger the fadein) then the drop down should stay shown until leaving the drop down element.

Here is the code I have so far:

$('#categories_link').live('click mouseleave', function(e){
    $('.categories').fadeIn(200, function(){
        $(this).live('mouseenter mouseleave', function(evnt){
            switch(evnt.type) {
                case "mouseenter":
                    $(this).stop(true, true)
                    $(this).data('visible', true)
                break;

                case "mouseleave":
                    $(this).data('visible', false)
                break;
            }
        })

        if(e.type == 'mouseleave') {
            if($('.categories').data('visible'))
                return;
            else
                $('.categories').fadeOut(200)
        }
    })
})
Was it helpful?

Solution

The structure is very problematic. Why do you add listeners on mouse leave?

Best thing you could do is

  • set the fadein to appear on mouseenter
  • set fadeout on mouseleave with a ~300-400ms delay using setTimeout()
  • set the actual dropdown to fade itself in on mouseenter, using a stop before that (ie: stop(true,true).fadeIn(200), but use clearTimeout() before this happens inside the event handler.
  • set the actual dropdown to fadeout on mouseleave

Actually you should use a stop(true,true) before all of these animations.

The logic behind this is that if the user hovers over the dropdown, the dropdown will try to fade itself in thus cancelling the fadeout that is queued to happen (you added an extra 200-300sec timer).

Another way to do it, is nest the dropdown inside the parent tag, so while you are hovered inside the dropdown, it won't fade away anyway (this also works with pure css)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top