Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html anchor tag onclick() and href execute simultaneously

Similar to HTML anchor link - href and onclick both? post, mine is:

<a href="/tmp/download.mp3" onclick="update();">Download link</a>

The update() method would send another HTTP GET method to the server to update the which file has been downloaded and update the database. From the HTML code, there are 2 GET requests being triggered together and only ONE will get the response (the href download response) from the server. The update() is not being executed. Is there any method that i can get both GET methods to be executed? Javascript and Jquery suggestions are welcomed!

like image 867
CheeHow Avatar asked Oct 08 '13 14:10

CheeHow


People also ask

Can you have onclick and href?

How to make this a tag working with href and onClick? The default behavior of the <a> tag's onclick and href properties are to execute the onclick , then follow the href as long as the onclick doesn't return false , canceling the event (or the event hasn't been prevented).

Can I use onclick in anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.

Does Onclick run before href?

onclick does trigger first, the href only goes once onclick has returned!

How do you add an onclick event to a hyperlink?

I would generally recommend using element. attachEvent (IE) or element. addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element. attachEvent / addEventListening allow multiple event handlers to be created.


1 Answers

Forget about the href and just do it all in the click function. You can navigate to another page after the update is complete. Here is my JQuery suggestion:

HTML

<a id="download" href="/tmp/download.mp3">Download link</a>

JavaScript (with JQuery)

$("#download").click(function(e){
    e.preventDefault();//this will prevent the link trying to navigate to another page
    var href = $(this).attr("href");//get the href so we can navigate later

    //do the update

    //when update has finished, navigate to the other page
    window.location = href;
});

NOTE: I added in an id for the a tag to ensure it can be selected accurately via JQuery

like image 69
musefan Avatar answered Sep 21 '22 12:09

musefan