Thursday, August 7, 2014

jQuery detect hover on an element

A navigation menu which expands when the user hovers over it, needs to detect when the user has stopped hovering in order to close the expansion. I came across a simple fix using angularJs which is able to detect the mouse hovering (coming and going) and display the menu accordingly.
$scope.openMenu = function() {
  // code to expand menu
};

$scope.checkCloseLanguageSelector = function () {
  if (isHovered($('#menu'))) {
    $scope.closeMenu = false;
  }
};
    
function isHovered(elt) {
  var temp = $(elt).parent().find(":hover");
  return temp.length == 1 && temp[0] == elt;
}

$scope.closeMenu = function() {
  // code to collapse menu
};
<div id="menu" ng-mouseover="openMenu()" ng-mouseleave="checkCloseMenu()">

</div>
The above code uses the angualrJs mouse over (ng-mouseover) and mouse leave (ng-mouseleave) directives to call functions which open and close the expanded menu. The mouse leave function checks if the user is still hovered over a given element and will close the expanded menu if appropriate.

No comments:

Post a Comment