t56k
t56k

Reputation: 6981

How do I add a second function to a button?

Say I have a standard HTML link like so:

<a href='https://whateverdomain.com/whatever.pdf' class='pdf-download'>

How can I both link to that .pdf and fire a jQuery function at the same time?

I've written this so far:

$('.pdf-download').addEventListener('click', function() {
  $.getJSON('/documents/email', function(email) {
    if (email.documentID && email.message == 'success') {
      console.log('Sending email...');
    };
  },
false);

But that just prevents my button from being clickable. I should mention that that listener is part of a bigger function:

function checkForAnswers() {
  var count = $('.pdf-checklist').filter(function() {
    return $(this).val() !== "";
  }).length;
  var total = $('.pdf-checklist').length;

  $('.pdf-download').addEventListener('click', function() {
    $.getJSON('/documents/email_press_ad', function(email) {
      if (email.documentID && email.message == 'success') {
        console.log('Sending email...');
      };
  }, false);

  if (count == total) {
    $('.pdf-download').removeClass('disabled');
    $('.pdf-download').removeAttr('disabled');
  } else {
    $('.pdf-download').addClass('disabled');
    $('.pdf-download').attr('disabled', 'disabled');
  }
  console.log(count + '/' + total);
}

$('.pdf-checklist').on('keyup', checkForAnswers);

Upvotes: 1

Views: 73

Answers (1)

Deckerz
Deckerz

Reputation: 2604

You could try just binding it with on

$(".pdf-download").on("click", function (e) {
    e.preventDefault();
    //do your stuff.

    //navigate to a click href via window.location
    window.location = $(this).attr('href');
});

So you cancel the click default event and manually force the url change after code is complete.

Editted according to comments.

Upvotes: 3

Related Questions