views:

25

answers:

3

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"?

+1  A: 
<a href="#" onclick="return false;">Some text</a>

Your jQuery-bound click functions should keep working.

Example:

http://jsfiddle.net/mU2dq/1/

Michael Robinson
+1  A: 

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.

GenericTypeTea
+1  A: 

To stop something from bubbling I always follow this:

$('myAnchor').live("click", function(e) {
    e.preventDefault();
    e.stopPropagation();

    //or if you want to stop all handlers
    e.stopImmediatePropagation();

    //code here

    //for IE etc.
    return false;
});
MRW
@MRW - He doesn't want to stop something bubbling, he wants to allow bubbling.
GenericTypeTea
Stop propagation will prevent it from bubbling
MRW
@GenericTypeTea - Ah I misinterpreted the "stop bubbling too"
MRW