Sparky
Sparky

Reputation: 98728

jQuery click(false) combined with a function

I want to prevent the "#" from being used because I'm using jQuery to do something else with a plugin on click...

<a href="#" id="mylink">My Link</a>

<script>
    $('#mylink').somePlugin().click(false);
</script>

The above works nicely whenever I've needed to block the default click.

Now I have something like this below and I want to prevent the default click behavior

<a href="#" id="mylink">My Link</a>

$('#mylink').click( function () {
    //  my code in here
});

I'm just not sure where/how to incorporate click(false) into the code above. Several things I've tried didn't work.

I know... I feel like a newbie asking this one.

Thank-you!

Upvotes: 2

Views: 9076

Answers (3)

Liam Bailey
Liam Bailey

Reputation: 5905

You need to do:

$('#mylink').click( function (e) {
        e.preventDefault();

        // the code here
    });

Upvotes: 5

Tomas Aschan
Tomas Aschan

Reputation: 60574

Different browsers handle this in slightly different ways, but jQuery does its best to cover your bases. There are three things you should know about, and at least the first two of them should be done to prevent normal click behavior in as many browsers as possible:

  1. return false; at the end of your click handler (as Am suggested) will stop the regular click action on a link in many browsers, including Internet Explorer and Google Chrome. return false; will also stop event propagation, which may or may not be what you wish. This is regular browser behavior, and does not have anything to do with jQuery.

  2. e.preventDefault();, as suggested by Liam is a jQuery method that prevents the default action to be triggered. "For example, clicked anchors will not take the browser to a new URL." This affects only the current item.

  3. e.stopPropagation(); is another jQuery method that prevents an event from bubbling. For example, if you have an anchor in a div, and the div has a click event hooked to it, the div's click event will be triggered even though you stop the anchors - unless you call this method.

Number 2 will cover almost all browsers, and with a combination of 1 and 2 you cover more or less all of them. Number 3 is only necessary if you don't want the event to bubble in the DOM tree, but I make it a habit to have it there, since mostly if I want to prevent the default action on a clicked element, I don't want anything except the code in this specific handler to happen.

Upvotes: 2

Roman
Roman

Reputation: 10403

$('#mylink').click( function (e) {
    return false;
});

Upvotes: 2

Related Questions