I have the following code. (You can copy it into a file to debug in Firefox, and see the outputs in the Console Tab in Firebug).
When I add onmouseover envent to the li tags, and move the mouse into the li area, the console info comes out.
The problem is when I moving the mouse from the image (Google logo) to the text under it, multiple info are print out. Why does the onmouseout event triggered, since I don’t leave the li area?
What should I do to prevent triggering the onmouseout events in this situation.
Thank you!!
<html>
<body>
<div>
<ul>
<li onmouseover="console.info('over')" onmouseout="console.info('out')" style="float:left;display:block;width:30%;height:200px;border: 2px solid red;">
<img src="https://www.google.com/intl/en_com/images/srpr/logo3w.png">
<br/>
<br/>
<a href="#">Google</a>
</li>
<li style="float:left;display:block;width:30%;">
<img src="https://www.google.com/intl/en_com/images/srpr/logo3w.png">
<br/>
<br/>
<a href="#">Google</a>
</li>
<li style="float:left;display:block;width:30%;">
<img src="https://www.google.com/intl/en_com/images/srpr/logo3w.png">
<br/>
<br/>
<a href="#">Google</a>
</li>
</ul>
</div>
</body>
</html>
Events bubble up the DOM tree. So when the cursor leaves the
imgelement, amouseoutevent is generated and triggers the event handler bound to the parentlielement.There are two ways you can deal with this situation:
Prevent the event from bubbling
If you want to prevent the event from bubbling up, you assign an event handler to the element the event originates and call the
eventobject’sstopPropagationmethod (orcancelBubbleproperty in IE):The problem is that you have to bind this handler to every child element, which is not very convenient. Therefore, the following way is easier to realise.
Test where the event originates
You can get a reference to the element where the event originates with
event.target(orevent.srcElementin IE). The event handler you bind to thelielement should look like this then:and call it with
Note that binding the event handlers inline, like you do, is bad design, as it mixes presentation with application logic. There are two other ways to bind event handlers
I recommend to read the articles about event handling on quirksmode.org.