Search code examples
jquerypreventdefault

jQuery preventDefault() stops onclick from working


I have a problem with jQuery preventDefault from running the onclick function of an tag. Here is my example: Avoid page jump on # click

$("#main a").bind("click", function (e) { 
    e.preventDefault();
}); 

I thought preventDefault would stop the default event (href="#"). But that it would let the "onclick" event stil fire. If I put the function inside my function it works. But I want to have different onclick functions on the links.


Solution

  • As adeneo and Jeremy have mentioned, do not use inline event handlers. They will interfer with your jQuery event handler.

    Simply merge the 2 functions into one, and it will work:

    $("#main a").bind("click", function (e) { 
        e.preventDefault();
    
        var p = $(this).position();
        $("#loader").css("top", p.top - 20);
        $("#loader").toggle();
    });
    

    JSFiddle


    If I put the function inside my function it works. But I want to have different onclick functions on the links.

    If you want to have different onclick functions on different links, then use classes (or IDs) and select them appropriately with jQuery.

    HTML:

    <div id="main">
        <p><a class="doSomething" href="#">I will NOT JUMP!</a></p>
        <p><a class="doSomethingElse" href="#">I will NOT JUMP</a></p>
    </div>
    

    jQuery:

    $("#main a.doSomething").bind("click", function (e) { 
        e.preventDefault();
    
        var p = $(this).position();
        $("#loader").css("top", p.top - 20);
        $("#loader").toggle();
    });
    
    $("#main a.doSomethingElse").bind("click", function (e) { 
        e.preventDefault();
    
        //Other code
    });
    

    JSFiddle demo