Search code examples
jqueryhtmljquery-eventsevent-bubbling

Event bubbling for parent of <a>, which returns false from onclick event listener


I try to make a common solution for the following task: onclick event listener for element

<a href="#">Some text</a>

must return false. It can stop page scrolling after click.

$("a[href='#']").bind("click", function () { return false; });  

It can stop scrolling but return false stop bubbling too! So, if I have the following code:

HTML

<div class="clickable">
   <a href="#">Text</a>
</div>

Javascript (JQuery)

$("a[href='#']").bind("click", function () { return false; });
$(".clickable").bind("click", function(){alert("It works!");})

and if I click on "Text", there is no alert.

Can I restore bubbling? Or, may be, there is any another common way to return false from onclick event listener of every such "a" tag? Or the only way is to add listener function(){alert("It works!");} on "a"?


Solution

  • Change your click function's signature to accept the event args and use preventDefault:

    $("a[href='#']").bind("click", function (e) { e.preventDefault(); });
    $(".clickable").bind("click", function(){alert("It works!");})
    

    Here's a working fiddle.