Question

Is it possible to assign url to the an anchor only when it got clicked?

<a href="http://example.com/">Token Link</a>

When the anchor got clicked, it will go to http://example.com/token=xxxxx/

I want to generate token only when it got clicked.

If possible, How?

thanks

Was it helpful?

Solution 2

Opening the link in another window using jQuery

$(document).ready(function () {
  $(".thisClass a").on("click", function(e){
    e.preventDefault(); // this prevents going to the original url or default behavior
    var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
    var newUrl = $(changedLink).attr('href');
    window.open(newUrl, '_blank');

  });

});

// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.

// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
  event.preventDefault();
  var aLink = document.getElementById('theLink');
  var theOldLink = aLink.getAttribute("href");
  aLink.setAttribute('href', theOldLink + "/token=xxxx");
  var theNewLink = aLink.getAttribute("href");
  window.open(theNewLink, "_blank");

}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code

 <div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
 onclick="changeTheLink()">Here is a link</a></div>

OTHER TIPS

you can handle the event and change the href like this.

$("a").on("click", function() {
   $(this).attr("href", $(this).attr("href") + "/token=xxxx");
});

you can also directly navigate the user to a different url, without changing.

$("a").on("click", function(ev) {
   document.location.href = "//something-different.com";
   ev.preventDefault();
   return false;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top