What can you do is attach even to button instead if link and return false
for anchor
HTML
<a href="http://www.somesite.com/sometrack.mp3" onclick="return false;">
<button id="button"> Download </button>
</a>
Jquery
$(function () {
$('#button').on('click', function () {
trackDownload();
alert($(this).parents('a').attr('href'));
window.location = $(this).parents('a').attr('href');
});
});
function trackDownload() {
alert('Track is getting download');
}
if you want to open in new tab use window.open($('#myanchor').attr('href'));
DEMO
As specified that trackDownload() in comments that it is ajax function what you can do is
$('#button').on('click', function () {
trackDownload($(this).parents('a')); // pass your link to this function
});
function trackDownload(element) {
$.ajax(
url: 'yoururl',
type: 'post',
... // all other parameter you want to pass
success: function () { // success when ajax is completed
window.location = element.attr('href'); // change url only when ajax is success
}
}
But if you want to attach click event to link only then you can do the same, just attache the event to link
<a id='music' href="http://www.somesite.com/sometrack.mp3" onclick="return false;">
<button> Download </button>
</a>
JS
$(function () {
$('#music').on('click', function () {
trackDownload();
alert($(this).attr('href'));
window.location = $(this).attr('href');
});
});
You can also look at this for more alternatives How can I simulate a click to an anchor tag?