207

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

Mahdi Alkhatib
  • 1,954
  • 1
  • 29
  • 43

12 Answers12

288
document.getElementById('yourLinkID').click();
arik
  • 28,170
  • 36
  • 100
  • 156
  • 22
    Actually, so far it worked in all browsers I tried, including IE, Safari, Chrome, Firefox and Opera. – arik Jan 29 '12 at 17:17
  • 10
    Note that if the a link has `target="_blank"` property, the browser's popup blocker will be activated for the new window. – wonsuc Feb 26 '19 at 06:11
  • I love you [more words here to fill minimum] – clamum Apr 04 '23 at 21:04
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";
Fabien Ménager
  • 140,109
  • 3
  • 41
  • 60
  • 59
    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." – cazlab Apr 22 '12 at 15:06
  • 15
    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" http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox – A.D. Jun 04 '14 at 08:12
  • 7
    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! – ajeh Mar 02 '15 at 19:36
  • This method was helpfull in PyQT4. click() call was not working for me. Thanks! – VilleLipponen Aug 14 '19 at 21:43
  • 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. – Random Elephant Jan 08 '20 at 13:03
  • This saved my project in a tricky case that required a page reloading when redirecting programmatically – Luis Febro Feb 02 '20 at 01:34
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;
    }
}
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
  • 5
    Matthew is correct, and http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox has some more info about why. Cross browser is fun :) – Dan F May 24 '09 at 01:57
  • 4
    it doesn't respect the `target` attribute or `` – Vitim.us Nov 09 '15 at 19:21
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>
Canavar
  • 47,715
  • 17
  • 91
  • 122
14

The jQuery way to click a link is

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

For mailTo link, you have to write the following code

$('#LinkID')[0].click();
Muhammad Waqas Iqbal
  • 3,244
  • 1
  • 20
  • 9
  • 2
    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. –  Feb 02 '16 at 07:11
  • 2
    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 points – Muhammad Waqas Iqbal Mar 12 '16 at 02:47
  • 3
    I tried this and the mailTo link doesn't work in React Native. Use this: window.location.href = "mailto:address@gmail.com"; – fungusanthrax Mar 10 '17 at 19:11
  • 4
    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. – Mmm Aug 13 '18 at 16:24
  • Firefox browser: This works for but not for an – Dimitrios Ververidis Aug 30 '18 at 11:08
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>
Reporter
  • 3,897
  • 5
  • 33
  • 47
  • There is a syntax error in showed code. One or two closing braces are missing. I added them via editing. – Reporter Sep 21 '20 at 09:38
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.

maus
  • 80
  • 7
  • 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 ... – historystamp Jan 02 '19 at 00:54
  • i think you're correct historystamp. He's creating a mouseevent and then immediately overwrites it with a new event. – John Lord Jul 06 '20 at 20:19
  • The click() method simulates a mouse-click on an element. https://www.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. – historystamp Feb 02 '23 at 17:47
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.

Jas Panesar
  • 6,597
  • 3
  • 36
  • 47
  • 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. – Scott Tovey Jan 23 '20 at 22:30
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.

akway
  • 1,738
  • 4
  • 21
  • 20
  • 2
    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. – dxvargas May 04 '17 at 21:55
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://stackoverflow.com/a/42907920/2361131

gawkface
  • 2,104
  • 2
  • 27
  • 29
-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()
  }
}
Vontei
  • 1,727
  • 2
  • 14
  • 16
-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.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198