0

I'm trying to create a simple constructor for eventListeners mouseover/out, but I ran into the one error - my object constructor HoverIntent does not want to recognize the this.elem value inside own method this.over?

P.S. Forgive me for such insane indents in the code, they are placed by the internal editor at insertion.

 function HoverIntent(elem) {

   this.elem = elem; // recognize normaly
   this.over = function() {
    var tooltip = document.createElement('div');
    tooltip.className = "tooltip";
    tooltip.innerHTML = "some-usefull-text";

     tooltip.style.left = this.elem.getBoundingClientRect().left + 'px'; 
            // this.elem - getting an error
     tooltip.style.top = this.elem.getBoundingClientRect().bottom + 5 + 'px'; 
            // this.elem - getting an error

     document.body.appendChild(tooltip);
   };
   this.out = function() {

    var current = document.getElementsByClassName('tooltip')[0];
     document.body.removeChild(current);
   };
 };

  elem.addEventListener( 'mouseover', new HoverIntent(elem).over );
  elem.addEventListener( 'mouseout', new HoverIntent(elem).out );
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <style>
 
 .clock {
     border: 1px dashed yellow;
     padding: 5px;
     display: inline-block;
     background: red;
     position: absolute;
     left: 0;
     top: 0;
 }

  </style>
</head>
<body>
 
 <div id="elem" class="clock">
   <span class="hours">14</span> :
   <span class="minutes">45</span> :
   <span class="seconds">10</span>
  </div>

  <script>
  </script>

</body>
</html>
Sviat Kuzhelev
  • 1,758
  • 10
  • 28

1 Answers1

1

Replace

this.over = function() {

with

this.over = () => {

This will cause the listener to be in the context of its constructor, and not the DOM element it was triggered on

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151