Search code examples
jqueryhtmlmouseleavemouseout

Select triggers mouseout/mouseleave event


I hide the following div -

<div id="testDIV" style="background-color: #4cff00; padding: 20px;">
        <select>
            <option>OptionA</option>
            <option>OptionB</option>
        </select>
    </div>

with this code -

$("#testDIV").mouseleave(function () {
            $(this).animate({ 'opacity': 0 }, 500, function () { $(this).remove(); });
        });

If user select an option the mouseleave also triggers...

How can I disable the mouseout/mouseleave events when user select an option.


Solution

  • I've put your code in a jsfiddle to test, and on MacOs X, I don't have the issue your having.

    I'm specifying the OS, because styling is different on Windows and Mac Os X.

    Could it be that your options are going out of your div when the select is open ?

    This would explain the behaviour. The mouse would be out of the div when it's selected.

    If it's the case, the solution would be to set a height big enough so that the options wouldn't go out of the div.

    Hope it helps you.

    EDIT:

    You can test the target of the event with "this" which is the element attach to the event. If the are different, then you don't trigger the hide function.

    $("#testDIV").mouseleave(function (event) {
        if (event.target !== this) return;
    
        event.stopImmediatePropagation();
        $(this).animate({ 'opacity': 0 }, 500, function () {
        $(this).remove(); 
      });
    });