12

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?

markzzz
  • 45,272
  • 113
  • 282
  • 475

4 Answers4

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

    ...

    if (someCondition) {
      //do stuff
    } else {
        location.href = $(this).attr('href');
    }
});
coolguy
  • 7,728
  • 9
  • 43
  • 71
  • 1
    Note that this opens the link in the same tab even if it was clicked with CMD (Mac) or CTRL (Windows, Ubuntu) pressed. – kslstn Jan 26 '20 at 13:46
5

Just move the preventDefault inside the if/else statement:

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

    ...

    if (someCondition) {
        e.preventDefault();

        ... code ...

    } else {
        ... execute the link
    }
});
Mottie
  • 79,894
  • 29
  • 121
  • 237
3

Take a look: Jquery Location Href?

Basically you can use window.location.href = 'http://example.com';

Community
  • 1
  • 1
Sem
  • 4,199
  • 3
  • 31
  • 51
1

Just put the e.preventDefault(); inside the condition?

Mike Sav
  • 13,975
  • 27
  • 94
  • 132