Search code examples
javascriptjqueryhtmlonclickevent-bubbling

<A>nchor's href being overridden by containing <div>'s onclick


When I click on the following link inside the outer div, I get the confirm statement, but after clicking 'OK', nothing happens.

HTML:
<div onclick="toggleExerciseDetails($(this),true)" class="clickable">
...
    <a target="_blank" href="http://iPUMPit.local/exercises/delete/275"
        onclick="cancelPropagation(event);return confirm('Are you sure you want to delete this exercise?');"
        title="Delete this exercise" class="icon icon_delete"></a>
</div>

JavaScript:

// cancels propagation of an event to the outer element event
function cancelPropagation(e) {
    if (!e)
        var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

Why isn't my click following the url?

Thanks :)


Solution

  • Use .stopPropagation():

    $('div.clickable a').click(function(e) {
        e.stopPropagation();
    });​
    

    jsFiddle example.

    This will make your link clickable but not allow the event to bubble up to the div, while keeping the div clickable.