Search code examples
jqueryhoverintent

keep second element while mouse leave (hover) first element


I try to create a div-element by hover over an element using the plugin hoverIntent.

<div class="element" style="with: 100%; height: 50px; border: 1px solid #000, margin: 5px">Main element</div>

Will get:

<div class="element" style="with: 100%; height: 50px; border: 1px solid #000, margin: 5px">Main element</div>
<div class="element new" style="with: 100%; height: 50px; border: 1px solid #000, margin: 5px">New element</div>

hoverIntent:

$(document).hoverIntent({
        over: function() {
            $(this).after('<div class="element new" style="with: 100%; height: 50px; border: 1px solid #000, margin: 5px">New element</div>');
        },
        out: function(){
            $('.new').slideUp(200, function() { $(this).remove(); });
        },
        selector: '.element'
});

I don't know how to fix the problem, that the new element always disapears as the user moves the mouse from the first element to the second. The new element should still be shown if the user moves the mouse over the main element or the new element. Only if the mouse moves somewhere else, the new element should disappear.


Solution

  • Despite your class-selector, the hoverIntent will trigger for that one element you hover over at the initial state, therefore the out-function will trigger for this element. The new element is not included here.

    You will see that of you look at the output of console.log($(this)). Only one object is included (demo) So only for that element in $(this) the out-function will work.

    I would recommend to wrap your elements into another div:

    HTML

    <div class="wrapper">
        <div class="element" style="with: 100%; height: 50px; border: 1px solid #000, margin: 5px">Main element</div>
    </div>
    

    jQuery

    $(document).hoverIntent({
        over: function () {
            $(this).append('<div class="element new" style="with: 100%; height: 50px; border: 1px solid #000, margin: 5px">New element</div>');
        },
        out: function () {
            $('.new').slideUp(200, function () {
                $(this).remove();
            });
        },
        selector: '.wrapper'
    });
    

    Demo

    To wrap you elements dynamically into a div you can use this snippet:

    var wrapper = $('<div />').addClass('wrapper');
    $('.element').wrap(wrapper);
    

    Demo 2