Wayne Pan

tech | js | ui | ajax | life | mobile
Filed under: ,

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)) {
      doStuff();
    }
};
div.on('mouseover', over, this, 'divId');

Posted by Wayne on Wednesday, September 5th, 2007


You can follow any responses to this entry through the magic of "RSS 2.0" and leave a trackback from your own site.

4 Responses to “onMouseOver and Child Elements”

Post A Comment

mt