Brig Lamoreaux
Brig Lamoreaux

Reputation:

How to navigate href in anchor tag via JavaScript

Is there an easy way to have JavaScript mimic a User clicking an anchor tag on a page? That means the Referrer Url needs to be set. Just setting the document.location.href doesn't set the Referrer Url.

<script>
  $(document).ready(function () {
    $("a").click();
});
</script>

<a href="http://example.com">Go here</a>

This doesn't work because there isn't a Click() event setup for the link.

Upvotes: 8

Views: 28679

Answers (5)

rFarag
rFarag

Reputation: 21

document.location.href = "#wanted_Location";

Upvotes: 2

Gaurav Gandhi
Gaurav Gandhi

Reputation: 3201

There is a simpler way to achieve it,

HTML

<a href="https://getbootstrap.com/" id="fooLinkID">Bootstrap is life </a>

JavaScript

// Simulating click after 3 seconds
setTimeout(function(){
  document.getElementById('fooLinkID').click();
}, 3 * 1000);

Using plain javascript to simulate a click.

You can check working example here on jsFiddle.

Upvotes: 1

Svante Svenson
Svante Svenson

Reputation: 12488

Okay, referer doesn't get set using document.location (as per my other answer), might work with window.navigate(url)? If that doesn't work the following might, though it's quite - ehrm - ugly:

$(function() {
  $("a").each(function(){
    if($(this).click()){
      $('<form method="get" action="' + $(this).attr("href") + '"></form>').appendTo("body").submit();
      return false;
    }
  });
});

Upvotes: 0

Paolo Bergantino
Paolo Bergantino

Reputation: 488404

You could do:

window.location = $("a").attr("href");

If you want to keep the referrer, you could do this:

var href = $('a').attr('href');
$('<form>').attr({action: href, method: 'GET'}).appendTo($('body')).submit();

It is hackish, but works in all browsers.

Upvotes: 14

Svante Svenson
Svante Svenson

Reputation: 12488

Maybe something like this is what you're looking for?

$(document).ready(function () {
  $("a").each(function(){
    if($(this).click()){
      document.location.href = $(this).attr("href");
    }
  });
});

Upvotes: 1

Related Questions