13

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
  • 47,390
  • 120
  • 299
  • 507

4 Answers4

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

    ...

    if (someCondition) {
      //do stuff
    } else {
        location.href = $(this).attr('href');
    }
});
coolguy
  • 7,866
  • 9
  • 45
  • 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
  • 84,355
  • 30
  • 126
  • 241
4

Take a look: Jquery Location Href?

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

Community
  • 1
  • 1
Sem
  • 4,477
  • 4
  • 33
  • 52
1

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

Mike Sav
  • 14,805
  • 31
  • 98
  • 143
  • You are right, but a small note in the case of working with AJAX, you must cast e.preventionDefault() before starting your ajax and checking, this is in case you need to check something with ajax, in which case your answer won't work – Mahmoud Magdy Aug 09 '23 at 06:26