Question

I have an anchor element inside a div. I'm listening to both elements click event. When the user clicks the 'a' element, I need to prevent the click event bubble. But I need to keep the anchor working: the user has to be redirected to 'href' page:

HTML:

<div id="myDiv">
    <a id="myLink" href="www.website.com">Click me</a>
</div>

JS:

$("#myLink").click(function() {
    // DO SOME STUFF

    return false;   // To prevent bubble
});

// This event handler has to be called only when the user clicked inside the div, but outside the link
$("#myDiv").click(function() {
    // DO SOME STUFF
});

The problem is that the user is not beeing redirected to "www.website.com". How can accomplish this?

Was it helpful?

Solution

You are not preventing the event bubbling properly.

$("#myLink").click(function(e) {


    e.stopPropagation(); // this will prevent bubbling.
});

// This event handler has to be called only when the user clicked inside the div, but outside the link
$("#myDiv").click(function() {
    // DO SOME STUFF
});

You can read more about event.stopPropagation() here: http://api.jquery.com/event.stopPropagation/

If you want to redirect, you have to use:

window.navigate('url-goes-here');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top