Using jQuery to programmatically click an <a> link
Asked Answered
Y

9

62

I know this question has been asked before, but after a search on the web I can't seem to find a straight forward answer.

the HTML

<a id=myAnchor href=index.php>

the jQuery (Both of these do not work)

 $('#myAnchor').click();

or

$('#myAnchor').trigger('click');

What is the simplest and most efficient way to achieve this?

Yggdrasil answered 31/1, 2012 at 14:43 Comment(6)
Click doesn't trigger the default behaviour of the link. This question has been asked many times before.Uziel
possible duplicate of Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?Uziel
duplicate: #2054098Marriage
I hope your HTML doesn't actually look like that. A normal HTML anchor looks like: <a id="myAnchor" href="index.php">Text</a> (with quotes and a proper closing tag).Blodget
@Cory: If you're not validating for XHTML, the quotes won't be required for those values.Preselector
@amnotiam: I know it's permitted to omit them, but the HTML spec does encourage them.Blodget
A
105

Try this:

$('#myAnchor')[0].click();

It works for me.

Apocope answered 28/5, 2014 at 7:0 Comment(7)
This worked for me when literally nothing else has. Thank you a great deal! +1Duly
This has problems with legacy browsers. Don't use it if you need broad compatibility.Preselector
I was looking for a Greasemonkey way, and this worked! Many thanks.Deice
Thanks for this! I have been trying to figure out how to programatically click links for years. The gotcha for me was not having that "[0]" in there. What is that called, and why is it necessary?Jannajannel
Worked for me in IE Edge.Elmore
@EricHepperle-CodeSlayer2010, the [0] is a shorthand for .get(0) which returns the underlying DOM element to which the JQuery object is refers. That allows you to call the .click() method directly on the DOM element, which works, rather than on the jQuery object, which does not work.Psychoneurotic
@10GritSandpaper Aha... thanks for explaining that! I get it now.Jannajannel
P
35
window.location = document.getElementById('myAnchor').href
Preselector answered 31/1, 2012 at 14:43 Comment(4)
I prefer this method personally, as it avoids the need to create a 'faked' event.Cain
This was once a popular way to redirect to a link, somehow it became a lost ancient technology nowadays :)Sungsungari
@RoryMcCrossan only when the purpose of an anchor is to redirect you. What if it is not? What if it opens a modal? Or sends an ajax request? Or loads a page via pjax?Dope
In those cases then you should just call the function that performs those actions directly, instead of faking a click event on a button.Cain
W
25

Click just triggers the click event / events not the actually "goto-the-links-href" action.

You have to write your own handler and then your $('#myAnchor').trigger('click'); will work...

$("#myAnchor").click(function(event)
{
  var link = $(this);
  var target = link.attr("target");

  if($.trim(target).length > 0)
  {
    window.open(link.attr("href"), target);
  }
  else
  {
     window.location = link.attr("href");
  }

  event.preventDefault();
});
Wendalyn answered 31/1, 2012 at 14:54 Comment(1)
My favorite as it addresses the issue of target. Does it trigger pop-up blockers though?Smog
S
4
<a href="#" id="myAnchor">Click me</a>

<script type="text/javascript">
$(document).ready(function(){
    $('#myAnchor').click(function(){
       window.location.href = 'index.php';
    });
})
</script>
Stipel answered 31/1, 2012 at 14:57 Comment(0)
M
4

Add onclick="window.location = this.href" to your <a> element. After this modification it could be .click()ed with expected behaviour. To do so with every link on your page, you can add this:

<script type="text/javascript">
    $(function () {
        $("a").attr("onclick", "window.location = this.href");
    });
</script>
Mischa answered 8/10, 2013 at 15:35 Comment(1)
Just fyi: Doesn't work in IE7. DIE, IE7, DIE! Otherwise very nice workaround!Gorrian
R
4

I tried few of the above solutions but they didn't worked for me. Here is a link to the page which worked for me automatically click a link

Above link has many solutions and here's the one which worked for me,

    <button onclick="fun();">Magic button</button>

    <!--The link you want to automatically click-->
    <a href='http://www.ercafe.com' id="myAnchor">My website</a>

Now within the <script> tags,

<script>

     function fun(){
          actuateLink(document.getElementById('myAnchor'));
     }

     function actuateLink(link)
     {
          var allowDefaultAction = true;

          if (link.click)
          {
              link.click();
              return;
          }
          else if (document.createEvent)
          {
              var e = document.createEvent('MouseEvents');
              e.initEvent(
                   'click'     // event type
                   ,true      // can bubble?
                   ,true      // cancelable?
              );
              allowDefaultAction = link.dispatchEvent(e);           
          }

          if (allowDefaultAction)       
          {
              var f = document.createElement('form');
              f.action = link.href;
              document.body.appendChild(f);
              f.submit();
          }
    }

</script>

Copy paste the above code and click on clicking the 'Magic button' button, you will be redirected to ErCafe.com.

Roll answered 14/2, 2014 at 7:9 Comment(1)
This is the only thing that worked for my situation! Some people even say the jQuery click simply works--not at all for me. This solution is awesome.Dwt
B
1

I had similar issue. try this $('#myAnchor').get(0).click();this works for me

Boeschen answered 26/4, 2020 at 6:55 Comment(0)
A
0

If you are using jQuery, you can do it with jQuery.trigger http://api.jquery.com/trigger/

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
    <a id="foo" onclick="action()"></a>
    <script type="text/javascript">
        function action(){
            window.location.replace("https://mcmap.net/q/145672/-using-jquery-to-programmatically-click-an-lt-a-gt-link/5526354")
        }

        $("#foo").trigger("click");
    </script>
</body>
</html>
Anderlecht answered 29/4, 2016 at 8:19 Comment(0)
U
0

Try this for compatibility;

<script type="text/javascript">
        $(function() {
            setTimeout(function() {
                window.location.href = $('#myAnchor').attr("href");

            }, 1500);
        });
    </script>
Unto answered 5/2, 2019 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.