Matija Milković
Matija Milković

Reputation: 2458

Calling a function when neither of two elements is being hovered?

My idea is to have two variables, insideLink that marks if I'm currently hovering over my menu and insideBox that checks if I'm hovering over Div container.

And if I leave I check if I'm also out of the other element, if I'm out of both I call the closeboth function that closes them both.

I tried doing it like this, but it doesn't work. Box closes right away after I move away from the menu link.

I suppose setTimeout would help but, but my attempts with that didn't work quite well. Any ideas?

$(linkID).hover(function() {
    insideLink=1;
    console.log("Its over Link");
},function() {
    insideLink=0;
    if (insideBox==0) {
      console.log("Its outside both elements, closebox"); 
      closebox();
    }
});

$(open).hover(function() {
    insideBox=1;
    console.log("Its inside box");
},function() {
    insideBox=0;
    if (insideLink==0) {
      console.log("Its outside both elements, closebox");
      closebox();
    }
});

Upvotes: 1

Views: 79

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173552

Since the mouseout of the link gets triggered before the mouseover of the box, one way is to use setTimeout():

insideLink=0;
setTimeout(function() {
    if (insideBox==0) {
        console.log("Its outside both elements, closebox"); 
        closebox();
    }
}, 100);

It suspends the box closing action for 100ms, which should be enough for the mouseover event to get fired that sets insideBox to 1. The same can be applied to the .hover() of the box.

Upvotes: 1

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

I guess you mean something like this:

    <div  id="outerDiv" onmouseover="checkMouse()">
        Outer DIV <br />
        <div id="innerDiv">Inner DIV 
            <br /> Inner DIV <br />
        </div>
        Outer DIV <br />
    </div>

    <script type="text/javascript">
        function checkMouse(){

            if(window.event.target.id == 'outerDiv'){
                console.log( 'indise outer div');
            }
            else{
                console.log( 'indise inner div');
            }
        }
    </script>

Upvotes: 0

Related Questions