0

I have a link and I cancel the "click" event with .preventDefault method to check if a user is logged in. If the user is logged in with the correct role I want to continue with the click effect following the link, home?

jQuery('.btn-read-more').on('click', function(e) {
    e.preventDefault();
    console.log(e.currentTarget);
    var data = {
        action: 'is_user_logged_in'
    };

    jQuery.post(ajaxurl, data, function(response) {
        console.log(response);
        if (response === 'no') {
            jQuery('#modal_login_form_div').modal('show');
        } else if (response === 'ccwdpo_user' || response === 'ccwdpo_customer') {
            //e.currentTarget.click();
            //console.log(e.currentTarget);
            window.location = jQuery(this).attr("href");    
        }
    });
});

For now, I solved with:

jQuery('.permalink').on('click', function(e) {
    e.preventDefault();
    var data = {
        action: 'is_user_logged_in'
    };

    var permalink = jQuery(this).attr('href');
    //console.log(permalink);
    jQuery.post(ajaxurl, data, function(response) {
        console.log(response);
        if (response === 'no') {
            jQuery('#modal_login_form_div').modal('show');
        } else if (response === 'ccwdpo_user' || response === 'ccwdpo_customer') {
            window.location = permalink;
        } else {
            jQuery('#modal_error_div').modal('show');
        }
    });
});
  • `this` isn't what you think it is inside the post callback. Store a reference to `this` or the `href` outside the post – charlietfl Mar 31 '19 at 19:32

1 Answers1

0

This will do what you want. Get the href value from the event and set window.location:

document.querySelector('a').onclick = ev => {
  // Prevent default
  ev.preventDefault();
  // Continue with action (note this does not handle if other attributes, such as `target="_blank"` is set)
  window.location = ev.target.getAttribute('href');
};
<a href="https://stackoverflow.com">Go to google</a>
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33