Reliable "mouse center" without jQuery

I searched everywhere and I cannot find a reliable mouseenter event.

The closest I found: mouseenter without jQuery

 function contains(container, maybe) { return container.contains ? container.contains(maybe) : !!(container.compareDocumentPosition(maybe) & 16); } var _addEvent = window.addEventListener ? function (elem, type, method) { elem.addEventListener(type, method, false); } : function (elem, type, method) { elem.attachEvent('on' + type, method); }; var _removeEvent = window.removeEventListener ? function (elem, type, method) { elem.removeEventListener(type, method, false); } : function (elem, type, method) { elem.detachEvent('on' + type, method); }; function _mouseEnterLeave(elem, type, method) { var mouseEnter = type === 'mouseenter', ie = mouseEnter ? 'fromElement' : 'toElement', method2 = function (e) { e = e || window.event; var related = e.relatedTarget || e[ie]; if ((elem === e.target || contains(elem, e.target)) && !contains(elem, related)) { method(); } }; type = mouseEnter ? 'mouseover' : 'mouseout'; _addEvent(elem, type, method2); return method2; } 

The only problem is that when I run it:

 _mouseEnterLeave(ele, 'mouseenter', function(){ console.log('test'); }); 

I get 40-47ish (every time every time) every time the listener starts.

I also tried Quirksmode: http://www.quirksmode.org/js/events_mouse.html#mouseenter

 function doSomething(e) { if (!e) var e = window.event; var tg = (window.event) ? e.srcElement : e.target; if (tg.nodeName != 'DIV') return; var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement; while (reltg != tg && reltg.nodeName != 'BODY') reltg= reltg.parentNode if (reltg== tg) return; // Mouseout took place when mouse actually left layer // Handle event } 

However, this one was extremely unreliable, and not only he suggested that parent / element was a DIV . This should be more dynamic. This is for the / script library, so I cannot enable jQuery.

In short, I have an element that is hidden until the mouse moves. When it moves, it appears as long as the mouse moves OR, if the mouse hangs over the element itself. Less code would be simple simply because only WebKit did not support mouseenter natively, and from the first example it seems like it has such a huge chunk of code to support Chrome for a small user interface.

+6
source share
1 answer

Is it possible to simply abandon the mouseenter and use mousemove ? This helps to display it when the mouse moves. To keep it visible when it depends directly on the element, just use CSS.

 #your_element { display: none; } #your_element:hover { display: block; } 
+3
source

Source: https://habr.com/ru/post/904036/


All Articles