Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 736
Tj Gienger Avatar asked Jul 19 '14 01:07

Tj Gienger


1 Answers

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

like image 59
Tj Gienger Avatar answered Oct 29 '22 11:10

Tj Gienger