Search code examples
jqueryhoverintent

Disabling hover event with the .not() method


I have the following code and I can't figure out why the hoverIntent event is firing although I assign the selected-food class to the li element on click.

Here is a jsfiddle: http://jsfiddle.net/7uPcc/2/

Expected behaviour: When a list item is clicked, the selected-food class is assigned to it (works fine) and the hidden div containing ingredients is not shown on hover. I'm trying to achieve this with the .not() method.

Actual behaviour: The hidden div is shown on hover although the hovered item has the selected-food class assigned.

HTML

<ul>
    <li class="food-name">Food 1
        <div class="food-ingredients">
            <ul>
                <li>Ingredient 1</li>
                <li>Ingredient 2</li>
                <li>Ingredient 3</li>
            </ul>
        </div>                    
    </li>
    <li class="food-name">Food 2
        <div class="food-ingredients">
            <ul>
                <li>Ingredient 1</li>
                <li>Ingredient 2</li>
                <li>Ingredient 3</li>
            </ul>
        </div>
    </li>
</ul>

CSS

.food-ingredients {
    display: none;
}

.selected-food {
    color: red;
}

Javascript

$('.food-name').not('.selected-food').hoverIntent({
    over: function() {
        $(this).children('.food-ingredients').show();
    }, 
    out: function() {
        $(this).children('.food-ingredients').hide();
    },
    timeout: 300
});

$('.food-name').click(function() {
    $(this).toggleClass('selected-food');
});

When I test the $('.food-name').not('.selected-food') selector in the console I get the expected result (i.e. list items with the selected-food class are not returned)


Solution

  • The hoverIntent event is bound to the elements on page load. At that time no elements have the class 'selected-food', so all of them trigger the hoverIntent event, even if you later add the 'selected-food' class to them.

    Here is a working example:

    $('.food-name').hoverIntent({
        over: function() {
            if (!$(this).hasClass('selected-food')) {
                $(this).children('.food-ingredients').show();
            }
        }, 
        out: function() {
            $(this).children('.food-ingredients').hide();
        },
        timeout: 300
    });
    
    $('.food-name').click(function() {
        $(this).toggleClass('selected-food');
    });
    

    Link to jsfiddle: http://jsfiddle.net/7uPcc/8/