80

How to programmatically trigger the click on a link using jQuery?

2
  • 2
    be careful of being flagged as a malicious site with javascript that does that... Clicking for a user is a very unhonourable thing to do Commented Aug 8, 2014 at 14:44
  • 1
    There are legit use cases for this. If the user has already clicked on something else to trigger a process that involves this click, and the user understands what is going on, I don't see the problem. Commented Nov 2, 2018 at 20:31

4 Answers 4

72
$('#your_link_id').click()

See the excellent jquery docs for more information

Sign up to request clarification or add additional context in comments.

Comments

68

If you have an anchor link:

<a id="my_link_id" href="something">My Link</a>

it will fail as other answers have mentioned. Calling .eq and .trigger('click') doesn't work for me, but this does:

$('#your_link_id').get(0).click();

In my specific case, I've assigned a blob url programmatically to the anchor's href.

6 Comments

After trying numerous different ways to click a span programmatically, this is the only one that works for me.
Thank you. Many years later this was a min-lifesaver.
This is the only one that worked for me. .trigger("click") executed the click event too many times that I would get an error: Uncaught RangeError: Maximum call stack size exceeded
thank you. .trigger("click") didn't work me either. this does .get(0).click(); :)
So does anyone can explain why .get(0).click() works and..click() doesn't?
|
26

You can use trigger:

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

Comments

15
$('#your_link_id').eq(0).trigger('click');

or you can use $('#your_link_id')[0].trigger('click');

is needed as jQuery returns an array and we cannot trigger click on multiple eventlinks. You have to target only a single element

2 Comments

Actually this will throw an error since you're on a native element by specifying [0]. To use jQuery methods on a specific item in a collection use filter methods such as .eq(0) or .first(), or wrap the whole thing in another $(). ex: $('#your_link_id').eq(0).trigger('click')
Interestingly, Marcy's solution doesn't work for me, whereas Sandeep's does. For some reason, $("#myDivIdentifier a").eq(0) still returns an array of one. $("#myDivIdentifier a")[0] gives me a single item that can be "click()"ed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.