5

I can't use jQuery for this part of the project due to various reasons. SO I need to detect this in vanilla js. I tried this but it doesn't work:

http://jsfiddle.net/qHfJD/

var myDiv = document.getElementById('foo');

myDiv.onmouseenter = function() { 
    alert('entered');
}

myDiv.onmouseleave = function() { 
    alert('left');
}
  • [This question](http://stackoverflow.com/questions/1638877/difference-between-onmouseover-and-onmouseenter) may help explain the difference between the events. – DOK Mar 07 '13 at 20:01

5 Answers5

5
myDiv.onmouseover = function(event) {
  if (this != event.currentTarget) { return false; }
  // mouse enter ...
}
myDiv.onmouseout = function(event) {
  if (this != event.currentTarget) { return false; }
  // mouse leave ...
}
ride
  • 129
  • 2
  • 2
3

The mouseenter and mouseleave events are proprietary to Internet Explorer, so if you aren't using IE, they won't work. Use mouseover and mouseout, instead.

By the way, you can use mouseenter and mouseleave via jQuery because jQuery simulates those events for you on non-IE browsers. See this article for tips on how to simulate mouseenter and mouseleave for yourself.

dgvid
  • 26,293
  • 5
  • 40
  • 57
2

mouseenter and mouseleave are proprietary MS events (that are actually pretty nice). If myDiv has no children, using mouseover / mouseout will have exactly the same effect.

http://jsfiddle.net/qHfJD/1/

Note: this original question and answer were very old and from a time when mouseenter and mouseleave were not well supported outside of IE. All modern browsers have supported these events on elements for quite some time now. They are generally preferred over mouseover/mouseout because the latter will trigger for each child of the element with the event listener in addition to the element itself.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 1
    this does not answer the question, which specified mouse "in" and "leave". Mouseover executes multiple times on elements that contain children. The closest answer I believe was given by ride on Feb 3rd. – Mark Entingh Jul 15 '17 at 01:24
-1

You are close. The function name is onmouseover and onmouseout

var myDiv = document.getElementById('foo');

myDiv.onmouseover = function() { 
  alert('entered');
}

myDiv.onmouseout = function() { 
  alert('left');
}
dremme
  • 739
  • 2
  • 10
  • 18
-2

Try: var myDiv = document.getElementById('foo');

myDiv.onmouseover = function() { 
    alert('entered');
}

myDiv.onmouseout = function() { 
    alert('left');
}

onmouseenter and onmouseleave are IE-only functionality.

dchiang
  • 67
  • 2