Search code examples
javascriptajaxprototypejs

Observing click of ajax code checks elements in order


I have a problem where I need the document observe click function (or something similar) to get elements in order from child out. The reason being is I want to have e.stopPropagation() on the child element, but the parent calls anyways because it is first in line.

For example:

   <script type="text/javascript"> 
    document.observe('click', function(e, el) {  
        if (el = e.findElement('.parent a')) { 
            e.stopPropagation();
        }
        if (el = e.findElement('.parent')){ 
            alert('parent');
        }
    });
    </script> 
    <div class="parent">
        <a href="test.html" target="_blank">Child Click Function</a>
        Parent Click Function
    </div>

In this example, parent gets found first, so the alert gets called. the reason I have to to do it this way rather than the element.observer is that its Ajax generated content and Prototype doesn't appear to have a live() function like jQuery.

Does anyone have a work around for this?

Thanks.


Solution

  • Prototype definitely does have a .live() equivalent and it is called Event.on(). It also works as an instance method, Element#on().

    document.on('click', '.parent', function(event, element) {
        if (!event.findElement('.parent a')) {
            alert('parent');
        }
    });