How do I programmatically click a link with javascript?
Asked Answered
D

12

208

Is there a way to click on a link on my page using JavaScript?

Dasha answered 23/5, 2009 at 23:33 Comment(4)
You can only preform a 'click' on input type="button" elements.Indebtedness
@Indebtedness I used .click() on an <a> element and it worked.Hutson
@Hutson In which browser did it work? And does it still work? :) thanx!Cultism
@Cultism I am afraid I do not remember anymore what exactly I was doing here. It was most likely Chrome I tested it on. Whichever version of Chrome was common in 2019.Hutson
S
289
document.getElementById('yourLinkID').click();
Sotelo answered 17/9, 2010 at 20:3 Comment(3)
Actually, so far it worked in all browsers I tried, including IE, Safari, Chrome, Firefox and Opera.Sotelo
Note that if the a link has target="_blank" property, the browser's popup blocker will be activated for the new window.Tabescent
I love you [more words here to fill minimum]Yesterday
H
48

If you only want to change the current page address, you can do that by simply doing this in Javascript :

location.href = "http://www.example.com/test";
Harleyharli answered 23/5, 2009 at 23:44 Comment(6)
Voted down because i dislike answers that answer around the use case rather than address it. "I presume this is your intention, and am unaware of your constraints, so with a conceptual sphere in a conceptual vaccum: use this."Drafty
I voted up, because I was looking for some nice solution of clicking mailto: link in userjs script. Definitely saved me time. I was prepared to create a element and making some "programmatic click" #809557Procne
I too tried calling click() method proposed elsewhere and above and it did not work in IE9, but setting location.href actually sent the email from the mailto: link. Great solution!Taboo
This method was helpfull in PyQT4. click() call was not working for me. Thanks!Buffon
Doesn't address my use case that's in the question, where I want to click a link. The link leads nowhere, but has other things tied to the click event. I don't want to change location.Bruit
This saved my project in a tricky case that required a page reloading when redirecting programmaticallyAstragal
T
47

This function works in at least Firefox, and Internet Explorer. It runs any event handlers attached to the link and loads the linked page if the event handlers don't cancel the default action.

function clickLink(link) {
    var cancelled = false;

    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0,
            false, false, false, false,
            0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
        window.location = link.href;
    }
}
Terrijo answered 24/5, 2009 at 1:16 Comment(2)
Matthew is correct, and #809557 has some more info about why. Cross browser is fun :)Formally
it doesn't respect the target attribute or <base target="frame">Rountree
B
19

Simply like that :

<a id="myLink" onclick="alert('link click');">LINK 1</a>
<a id="myLink2" onclick="document.getElementById('myLink').click()">Click link 1</a>

or at page load :

<body onload="document.getElementById('myLink').click()">
...
<a id="myLink" onclick="alert('link click');">LINK 1</a>
...
</body>
Broadcloth answered 23/5, 2009 at 23:37 Comment(5)
Yes but then some other click has to happen.Agueweed
Can't you do it on any event, like page load?Heated
thanks for help, but im using firefox 3 and it doesn't work, in error console says Error: document.getElementById("myLink").click is not a functionDasha
It seems like firefox doesn't support click method. and most of the answers, including mine, are not helpful :)Broadcloth
@Canavar: Try Click instead of clickElectorate
S
14

The jQuery way to click a link is

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

For mailTo link, you have to write the following code

$('#LinkID')[0].click();
Sonar answered 24/9, 2015 at 10:24 Comment(5)
This doesn't work .This is not the answer for the question he asked .i would have given a negative for this if i had some more points.Milliken
This doesn't work? Have your tried it? I hope you understand what "LinkID" means. I would be really surprised if someone now-a-days is backward enough to js without jQuery. Anyway, feel free to downvote after gaining some pointsSonar
I tried this and the mailTo link doesn't work in React Native. Use this: window.location.href = "mailto:[email protected]";Polybius
This didn't work for me either for clicking an a link. Using the [0].click() version works, which I believe is the same as the document.getElementById('yourLinkID').click(); answer.Socialization
Firefox browser: This works for <input> but not for an <a>Reeducate
R
6

For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.

<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>
Resigned answered 7/2, 2017 at 12:49 Comment(1)
There is a syntax error in showed code. One or two closing braces are missing. I added them via editing.Darin
T
4

Many of the above methods have been deprecated. It is now recommended to use the constructor found here

function clickAnchorTag() {
    var event = document.createEvent('MouseEvent');
    event = new CustomEvent('click');
    var a = document.getElementById('nameOfID');
    a.dispatchEvent(event);
}

This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.

Timeous answered 3/5, 2017 at 17:27 Comment(3)
I do not understand why event is being set twice. I do not see how event = new CustomEvent('click'); is reference event, so what is the point of var ...Janae
i think you're correct historystamp. He's creating a mouseevent and then immediately overwrites it with a new event.Huoh
The click() method simulates a mouse-click on an element. w3schools.com/jsref/met_html_click.asp Don't know why you're implying click method has been depreciated. It's on the W3 website.Janae
L
1

Instead of clicking, can you forward to the URL that the click would go to using Javascript?

Maybe you could put something in the body onLoad to go where you want.

Lands answered 23/5, 2009 at 23:40 Comment(1)
I posted to both questions because people are not going to naturally look up button information when they are dealing with an "a tag" link. They are technically unrelated.Nazarene
V
1

You could just redirect them to another page. Actually making it literally click a link and travel to it seems unnessacary, but I don't know the whole story.

Volney answered 24/5, 2009 at 1:4 Comment(1)
In my case, I don't know if the link has target "_blank", so I don't know if I should use location.href or window.open. It's shorter to dispatch a click. There are use cases, for instance you may want to fire an event like opening a modalbox.Grof
D
0

for those wanting to click all links that have a particular text content, this would work:

for (const a of document.querySelectorAll("a")) {
  if (a.textContent.includes("<your text to be searched here>")) {
    a.click();
  }
}

reference: https://mcmap.net/q/98838/-how-to-get-element-by-innertext

Divinize answered 17/8, 2021 at 22:10 Comment(0)
A
-2

Client Side JS function to automatically click a link when...

Here is an example where you check the value of a hidden form input, which holds an error passed down from the server.. your client side JS then checks the value of it and populates an error in another location that you specify..in this case a pop-up login modal.

var signUperror = document.getElementById('handleError')

if (signUperror) {
  if(signUperror.innerHTML != ""){
  var clicker = function(){
    document.getElementById('signup').click()
  }
  clicker()
  }
}
Asserted answered 5/8, 2015 at 0:16 Comment(0)
M
-6

You can't make the user's mouse do anything. But you have full control over what happens when an event triggers.

What you can do is do a click on body load. W3Schools has an example here.

Marketing answered 23/5, 2009 at 23:35 Comment(1)
@Neolit it was a bad link before it got 404'd anyways. No loss.Averill

© 2022 - 2024 — McMap. All rights reserved.