Search code examples
javascripteventsprototypejsdom-events

JS and Prototype : mouseover influencing overlying element, why?


I try to create a mouseover Event on a div wich containt a link. When the mouse pass over the div the background is apply to all div correctly, but when the mouse is over the link the background get apply only to the link, why?

The link IS in the div, so logically it should still call my event on the div.

-----------------------------------------------------------
|   |link|                                                |
-----------------------------------------------------------
<div id="a" style="width:100%;">
       <a href="">bob</a>
</div>

<script type="text/javascript">
    $("a").observe('mouseover', function(e) {
            Event.element(e).setStyle({backgroundColor: '#900'});
     });

    $("a").observe('mouseout', function(e) {
                Event.element(e).setStyle({backgroundColor: '#fff'});
    });
</script>

Solution

  • Use this inside your event handler to consistently reference the div the handler was bound to:

    $("a").observe('mouseover', function() {
      this.setStyle({backgroundColor: '#900'});
    });
    
    $("a").observe('mouseout', function() {
      this.setStyle({backgroundColor: '#fff'});
    });