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:
/
var myDiv = document.getElementById('foo');
myDiv.onmouseenter = function() {
alert('entered');
}
myDiv.onmouseleave = function() {
alert('left');
}
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/qHfJD/
var myDiv = document.getElementById('foo');
myDiv.onmouseenter = function() {
alert('entered');
}
myDiv.onmouseleave = function() {
alert('left');
}
Share
Improve this question
asked Mar 7, 2013 at 19:56
user967451user967451
1
- This question may help explain the difference between the events. – DOK Commented Mar 7, 2013 at 20:01
5 Answers
Reset to default 5myDiv.onmouseover = function(event) {
if (this != event.currentTarget) { return false; }
// mouse enter ...
}
myDiv.onmouseout = function(event) {
if (this != event.currentTarget) { return false; }
// mouse leave ...
}
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/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.
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.
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');
}
Try: var myDiv = document.getElementById('foo');
myDiv.onmouseover = function() {
alert('entered');
}
myDiv.onmouseout = function() {
alert('left');
}
onmouseenter and onmouseleave are IE-only functionality.