Search code examples
jqueryhovermouseentermouseleave

jQuery Hover on Two Separate Elements


I have two separate elements setup which appear on different parts of the DOM - the problem I am facing is that they are absolutely positioned and I can't wrap them in a container div.

I have setup a JSfiddle here - http://jsfiddle.net/sA5C7/1/

What I am trying to do is: move the elements in and out together - so that a user can move their mouse between either element and ONLY once they move off BOTH would it hide again ?

How can I set this up? Because at the moment, once I move off a single element - it fires the "leave event" for that element etc.


Solution

  • You could use two boolean variables that you set, each for every element. It gets true when you enter the element and false if you leave.

    And only when both are false on leaving => hide the elements.

    $(document).ready(function(){
        var bslider = false;
        var btest = false;
        $('#slider').mouseover(function() {
            bslider = true;
            $('#slider, #test').stop(true,false).animate(
                        {'margin-left':'20px'
                        });
        });
        $('#test').mouseover(function() {
            btest = true;
            $('#slider, #test').stop(true,false).animate(
                        {'margin-left':'20px'
                        });
        });
        $('#slider').mouseout(function() {
            bslider = false;
            if(!bslider && !btest)
            {
                $('#slider, #test').stop(true,false).animate(
                        {'margin-left':'0'
                        });
            }
        });
        $('#test').mouseout(function() {
            btest = false;
            if(!bslider && !btest)
            {
                $('#slider, #test').stop(true,false).animate(
                        {'margin-left':'0'
                        });
            }
        });
    });