Search code examples
javascriptjqueryjquery-eventsonmouseover

onmouseover not triggering more than once


I have a function which is called onmouseover that animates the element that was moused over down then, once the mouse has moved outside of the area that the element took up, animates the element back up. The function works fine but only works one time. So if I mouseover a second time the function is not triggered. I have to refresh the page in order to get the function to trigger again. Any assistance would be appreciated.

HTML:

<div class="frontDivcenter blueGradient shadow" id="front1" onmouseover="slideDown(this);">
        Hello
    </div>

Javascript:

function slideDown(item) {
    $(item).animate({
        top: '-100%'
    }, 250, 'easeInOutCubic');
    $(document).mousemove(function (e) {
        if (e.pageX < $(item).offset().left || e.pageX > ($(item).offset().left + $(item).width()) || e.pageY < $(item).offset().top || e.pageY > ($(item).offset().top + $(item).height())) {
            $(item).animate({
                top: '-200%'
            }, 250, 'easeInOutCubic');
        }
    });
};

Solution

  • You are unbinding the mouseover from the element, not mousemove from document

    Try with:

    function slideDown(item) {
        $item = $(item);
        $item.animate({
            top: '-100%'
        }, 250, 'easeInOutCubic');
    
        $(document).mousemove(function (e) {
            var offset = $item.offset(),
                width = $item.width(),
                height= $item.height();
    
            if (e.pageX < offset.left || e.pageX > ( offset.left + width) || e.pageY < offset.top || e.pageY > (offset.top + height )) {
    
                $(document).unbind("mousemove");
    
                $item.animate({
                    top: '-200%'
                }, 250, 'easeInOutCubic' );
            }
        });
    }