Tag Archives: nested

Mouseover / Mouseout on Nested Elements

Did I mention I’m code-sprinting over the next three days?  Actually, next two days – I just finished my first day today.

What’s code-sprinting?  It’s a trendy term for sitting down with your team, and plowing through code en masse, trying to get as much done as possible.  8 hour days, cookies, coffee, whiteboards, pizza, crashes, bugs, tickets, fixes, etc.  We’re trying to cram 3 weeks of work into 3 days.  Cool.

In case you don’t remember, I’m working on a project called Checkmark (or OLM…still undecided on the name) – a tool for Professors/TAs to receive student code submissions, and to facilitate easy marking and annotating of the submitted code.

So here’s something I learned today while coding:

Say you have some nested DIV’s, and the parent DIV has a mouseout trigger.  Something like this:

<div id="parent" onMouseOut="alert('Mouseout triggered on parent');">
  <div id="child_1">This is some child</div>
  <div id="child_2">This is another child</div>
</div>

As you would expect, the mouseout event will get triggered if you move your mouse over the parent DIV, and then move the mouse back out again.

But it also gets triggered when you move your mouse OVER any of the child DIV’s.

Say what?  That’s right – even though you’re still inside the parent DIV, the mouseout event got triggered.  I found this out today when I was trying to code dropdown menus in Javascript/CSS using Prototype – I could get the dropdown menus to appear find when I clicked on the appropriate button, but they’d disappear again as soon as I put my mouse over any of the sub-elements of the DIV.

So how did I fix this?  I found this example code, and adapted it for my purposes.  This code assumes that you’re using the Prototype Javascript library.

$('some_dropdown').observe('mouseout',
  function(event) {
     //We could probably replace the following with Event.element(event), but oh well.
     var target = $('some_dropdown');
     var mouse_over_element;  //What the mouse is currently over...
     //So let's check to see what the mouse is now over, and assign it to mouse_over_element...
     if( event.toElement ) {
        mouse_over_element = event.toElement;
     }
     else if(event.relatedTarget) {
       mouse_over_element = event.relatedTarget;
     }
     //In the event that the mouse is over something outside the DOM (like an alert window)...
     if(mouse_over_element == null) {
        return;
     }
     //Now we just make sure that what the mouse is currently over is NOT a descendant of
     //the dropdown, and that the target is not the current mouse_over_element (I can't
     //remember which case this covers, but it's important)
     if(!mouse_over_element.descendantOf(target) && target != mouse_over_element) {
        target.hide();
     }
   }
 );

And it works.  Whew!  Just thought I’d share that little snippit.