Search code examples
javascriptprototypejs

Observing click of element within element that has a separate click observe function


I have an element within another element and both have separate click functions. What I would like to do is ignore or stop the parent element if the child element has a click function. For example:

<div class="parent">
   <div class="child1">Child Click Function</div>
   Parent Click Function
</div>
<script type="text/javascript">
document.observe('dom:loaded',function(){
   if ($$('.parent') != undefined) {
      $$('.parent').invoke('observe','click', function(e) {    
         alert('parent');         
      });
   }
   if ($$('.child1') != undefined) {
      $$('.child1').invoke('observe','click', function(e) {    
         alert('child');         
      });
   }        
});
</script>

What happens is that when child1 is clicked, both that and parent are triggered since child1 is within parent. I would like disable/stop the observe when child is selected, but when you click on anything else inside parent, it works as it should.

Thanks.


Solution

  • You're encountering what's known as "event bubbling". Events on a given element bubble up the DOM until they reach the root node unless you explicitly stop the bubbling. Since it looks like you're using Prototype, updating your child's event handler to the following should do the trick:

    $$('.child1').invoke('observe','click', function(e) {    
        Event.stop(e);    
        alert('child');         
    });
    

    http://api.prototypejs.org/dom/Event/prototype/stop/