javascriptangularjshoverhoverintent

How do I add a delay for hovering an element in angularjs?


I have an element:

    <span ng-mouseenter="showIt()" ng-mouseleave="hideIt()">Hover Me</span>
    <div class="outerDiv" ng-show="hovering">
        <p>Some content</p>
        <div class="innerDiv">
            <p>More Content</p>
        </div>
    </div>

Here is the JS:

// mouseenter event
$scope.showIt = function () {
    $scope.hovering = true;
};

// mouseleave event
$scope.hideIt = function () {
    $scope.hovering = false;
};

And I want to be able to set a 500ms delay on the hover event.

I already had an answer to this question, but I can't post it for another 8 hours. I'll be back!


Solution

  • Like what most have mentioned on here already, I added a timer to the mouseenter event.

    // create the timer variable
    var timer;
    
    // mouseenter event
    $scope.showIt = function () {
        timer = $timeout(function () {
            $scope.hovering = true;
        }, 500);
    };
    

    The problem I had was that if I was scrolling past the item and the mouse cursor hit it, the popup would still occur half a second later. I want to be able to scroll past an item without the popup happening by accident.

    Putting the timeout in a variable allowed me to cancel the timeout. Which I do on a mouse leave event to ensure users don't accidentally triggering the popup.

    // mouseleave event
    $scope.hideIt = function () {
        $timeout.cancel(timer);
        $scope.hovering = false;
    };
    

    Here is a fiddle in case anyone wants to see it in action: jsfiddle