Search code examples
jquerystoppropagationevent-propagation

How to exempt an element within a tag from the latter's behavior?


On my page I have a large a element containing different things including a "open_modal" button that opens some Bootstrap modal window. When clicking anywhere within the a element I want normal behavior to occur, but clicking on the "open_modal" should only open the modal window (taken care of through Bootstrap modal classes).

HTML:

<a href='example.com'>
    <div class='open_modal'>doing something else</div>
</a>

Using stopPropagation() with the button successfully removes the a behavior from it but unfortunately it also removes the Bootstrap modal functionality attached to it so it doesn't do anything anymore:

$( '.open_modal' ).click(function(event) {    
    event.stopPropagation();
});

Any idea?


Solution

  • You should use preventDefault() instead of stopPropagation(). stopPropagation stops the event from bubbling up the event chain ( i.e, the events registered in the chain would not invoke ) while preventDefault prevents the default action the browser makes on that event ( i.e, prevents just the default behavior of the current event ).

    $( '.open_modal' ).click(function(event) {    
        event.preventDefault();
    });