Is it possible to trigger a click on a anchor link via javascript only (not Jquery - long story!).
We want to pass an anchor link's id into a function which will trigger the click, but have no idea how to trigger a click without jquery!
Thanks
Is it possible to trigger a click on a anchor link via javascript only (not Jquery - long story!).
We want to pass an anchor link's id into a function which will trigger the click, but have no idea how to trigger a click without jquery!
Thanks
In some browsers, you can just do something like document.getElementById(myelement).click()
(I'm fairly sure this is the case of IE only, but it could be available in more).
Since it's an <a>
tag you want to click, its default click event can be emulated fairly easily:
function clickLink(id) {
var tag = document.getElementById(id);
if( tag.onclick) {
var def = tag.onclick();
if( !def) return false; // event cancelled by handler
}
window.location.href = tag.getAttribute("href");
}
Note that this doesn't take into account event added with addEventListener
or any other events than the .onclick
property and onClick
attribute, and it doesn't open a new window/tab if the user Ctrl+Clicks or MMB-clicks.