How to programmatically trigger the click on a link using jQuery?
-
2be careful of being flagged as a malicious site with javascript that does that... Clicking for a user is a very unhonourable thing to doPopulus– Populus2014-08-08 14:44:45 +00:00Commented Aug 8, 2014 at 14:44
-
1There 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.Andrew Koster– Andrew Koster2018-11-02 20:31:13 +00:00Commented Nov 2, 2018 at 20:31
Add a comment
|
4 Answers
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
LjCode
After trying numerous different ways to click a span programmatically, this is the only one that works for me.
11teenth
Thank you. Many years later this was a min-lifesaver.
PouncingPoodle
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 exceededyohan.jayarathna
thank you.
.trigger("click") didn't work me either. this does .get(0).click(); :)Dejan Dozet
So does anyone can explain why .get(0).click() works and..click() doesn't?
|
$('#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
Marcy Sutton
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')
MartinG
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.