Search code examples
jqueryeventsstoppropagation

Confusion regarding event bubbling and stopPropagation and then permitting bubbling


My menus work like this: each menu item (e.g., Menu Item One below) is in a <td> in a table nested inside ANOTHER <td>. That outer <td> has some onclick event handler (here called "processMenuClick()").

<td onClick="processMenuClick(<item-dependent-arguments>);">
    <table>
        <tr>
            <td class="innermenuitem">Menu Item One</td>
       </tr>
    </table></td>

Under certain conditions I wish to prevent the menu from responding to clicks. In order to test how this will work, I make two buttons. One applies event.stopPropagation to each <td> of class "innermenuitem" like so:

<button onclick="javascript:stopit()">Test the disable menu functionality</button>

<script type="text/javascript">
function stopit()
{
    $("td.innermenuitem").click(function(event)
    {
        event.stopPropagation();
    })
}
</script>

This seems to work great. When I click the button, the menu stops responding to the clicks. But now say I want to re-enable the menu. The click handler is still undisturbed in the outer <td>. So I want my second button to DISABLE the stopPropagation that I've applied to the inner <td>. Does that make sense? If so, how is it done?

Note: Note that the above should allow me to disable the menu and re-enable it without having to rebind the outer <td> to its handler. This is important because the arguments that are passed to "processMenuClick()" are only known on the server. I would have to figure out a way to recall them through some kind of postback if I had to rebind the handler. But I figure since all I've done is stop bubbling the events up from the inner <td>, assuming there's a way to UNDO this (and permit events to bubble up again) I should be golden. But reading other threads it seems like stopPropagation is used for just one event, not like I am thinking of it, which is basically like a "status" on the <td>. Can somebody set me straight? (And hopefully solve the problem I've tried carefully to describe here?) Thanks.

Paragram


Solution

  • function startIt(){
         $('td.innermenuitem').off('click');
    }
    

    stop it should bind with the on method to make this as simple as possible.

    function stopIt(){
        $('td.innermenuitem').on('click', function(event){
           event.stopPropagation();
        });
    }