0
votes

I have a bunch of divs that can be hovered.

<div ng-controller="HoverController as hover">
  <div class="hoverable" data-number="1"></div>
  <div class="hoverable" data-number="2"></div>
  <div class="hoverable" data-number="3"></div>
</div>

What I'd like to do is, when each .hoverable div is hovered, set the value of hover.hoveredNumber to the data-number attribute of the hovered element.

There must also be a condition where no element is hovered, and the value of hover.hoveredNumber is 0.

I've considered using ng-mouseover and ng-mouseleave to manually trigger mouseover and mouseleave events for each of the hoverable divs, and from there, determine which element is hovered.

My issue is that each hoverable div also has a :hover style in the CSS. I understand that :hover is very reliable, but I don't trust the two separate mouse-detecting events to be as reliable, particularly if the user is moving their cursor very fast and one of the events is missed.

I expect there to be, at times, some discrepancy between which element is reflected in hover.hoveredNumber and the element that is currently displaying its :hovered style. The hoverable divs are also extremely close together and overlapping in some cases, and I'm concerned that the mouseover event of one div may fire before the mouseleave event of another, causing a discrepancy.

How can I guarantee accuracy as to which element is being hovered?

1
@RoqueSantos I am using AngularJS, not Angular2snazzybouche
well, I found another example here stackoverflow.com/a/22532856/2721661Roque Santos
@RoqueSantos these answers explain what I'd need to do in order to establish mouseover and mouseleave events, but I've already got that covered - my concern is their reliability and specific timingsnazzybouche
I understand but given those answers I see there's no hover event and the majority of people use the techniques described on those links.Roque Santos

1 Answers

1
votes

If you want it to be responsive, avoid ng-mouseover and ng-mouseleave. Those directives invoke AngularJS digest cycles with large computation overhead.

Instead use a custom directive:

angular.module("app",[])
.directive("detect",function() {
  return {
    link: postLink,
  }
  function postLink(scope,elem,attrs) {
    elem.on("mouseover mouseleave", function(e) {
      var $target = angular.element(e.target);
      var num = $target.attr("data-number") || '0';
      console.log("hover.hoveredNumber is",num);
    })
  }
})
.hoverable {
  background-color: red;
  height: 20px;
  width: 30px;
  text-align: center;
  border-radius: 10px;
}
  <script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <fieldset detect>
       <div class="hoverable" data-number="1">1</div>
       <div class="hoverable" data-number="2">2</div>
       <div class="hoverable" data-number="3">3</div>
    </fieldset>
  </body>