I am trying to trigger click event on hyperlink with jquery like the way below. Hyperlink does not have any id but it does have cssclass
$(document).ready(function () { $('.cssbuttongo').trigger('click'); });
The function above is not working. This is the hyperlink
<a href="hyperlinkurl" class="cssbuttongo">hyperlink anchor</a>
Thanks for the answers.
The native DOM method does the right thing:
This works regardless of whether the
href
is a URL, a fragment (e.g.#blah
) or even ajavascript:
.Note that this calls the DOM
click
method instead of the jQueryclick
method (which is very incomplete and completely ignoreshref
).Just want to let you guys know, the accepted answer doesn't always work.
Here's an example it will fail.
if
<href='/list'>
or you could append the href you got from jQuery to this
or jQuery way
Finally, invoke it to change the browser current page's url
or pop it out using
window.open(url)
Here's an example in JSFiddle.
I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an
<a>
tag doesn't seem to behave the same way you would expect with say, a input button.The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:
Edit:
I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.
I was facing a similar issue how to click a button, instead of a link. It did not success in the methods .trigger('click') or [0].click(), and I did not know why. At last, the following was working for me:
In addition to romkyns's great answer.. here is some relevant documentation/examples.
DOM Elements have a native
.click()
method.Relevant W3 documentation.
A few examples..
You can access a specific DOM element from a jQuery object: (example)
You can use the
.get()
method to retrieve a DOM element from a jQuery object: (example)As expected, you can select the DOM element and call the
.click()
method. (example)It's worth pointing out that jQuery is not required to trigger a native
.click()
event.Triggering a click via JavaScript will not open a hyperlink. This is a security measure built into the browser.
See this question for some workarounds, though.