onMouseOver and Child Elements

I maybe way behind on this and I’m not sure how I haven’t encountered this little quirk in javascript until now but apparently the onmouseover (and subsequently onmouseout) event fires repeatedly at unexpected times. For example if you add an event to a <div> that encompasses child elements, every time you pass over a child element you the onmouseover and onmouseout event fire sequentially.

This makes your onmouseover event handler execute many many many more times than you’d expect. Click here for an example for this in action. To get around this little nuisance of javascript you have to check if the event happens within the parent element and filter these out.

I’m currently in love with the Ext JS framework (and have been since Jack first published it on this blog) so the following solution is based on that framework. But other frameworks have similar event handling functions.

var div = Ext.get('divId');
var over = function(e, el, divId) {
// within returns whether or not event
// appears in this parent element.
    if(!e.within(Ext.get('divId'), true)) {
div.on('mouseover', over, this, 'divId');

4 responses to “onMouseOver and Child Elements”

  1. Anonymous says:

    Wayne, you may also like the convenience function addClassOnOver which handles this for you behind the scenes if you tell it to:

    Ext.get(‘divId’).addClassOnOver(‘your-class’, true);

    This registers the required event handlers and also automatically filters child elements for you if you pass the optional second argument of “true”.

  2. Wayne says:

    Thanks for the great tip! Good one liner to for CSS effects. However, I needed to do additional things other than adding a class.

  3. Daniel says:

    Thanks for posting this. I was wondering what was going on with this. It seems to me (Element).on(‘mouseover’,…) is not the same as the html attribute onmouseover. Anyway, thanks!

  4. pat says:

    Just curious if you could post the source of the page were you got this working on?

    – thanks