Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute a link after a preventDefault()?

Tags:

jquery

Code :

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

    ...

    if (someCondition) {
        ... code ...
    } else {
        ... execute the link
    }
});

I'd like, if someCondition is false, execute the original href of the link (so, go that link, changing the page). Is it this possible?

like image 708
markzzz Avatar asked Jun 08 '12 08:06

markzzz


People also ask

What does preventDefault () do?

The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

What is the opposite of event preventDefault ()?

As you probably might have already worked out based on the simple explanation above: the opposite of event. preventDefault() is nothing. You just don't prevent the event, by default the browser will allow the event if you are not preventing it.

Why include event preventDefault (); in a form script?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

Is there any significant difference between event preventDefault () vs return false to stop event propagation?

The main difference between return false and event. preventDefault() is that your code below return false will not be executed and in event. preventDefault() case your code will execute after this statement.


2 Answers

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

    ...

    if (someCondition) {
      //do stuff
    } else {
        location.href = $(this).attr('href');
    }
});
like image 183
coolguy Avatar answered Oct 07 '22 14:10

coolguy


Just move the preventDefault inside the if/else statement:

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

    ...

    if (someCondition) {
        e.preventDefault();

        ... code ...

    } else {
        ... execute the link
    }
});
like image 26
Mottie Avatar answered Oct 07 '22 12:10

Mottie