2

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

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Dancer
  • 17,035
  • 38
  • 129
  • 206
  • possible duplicate of [Is it possible to trigger a link's (or any element's) click event through JavaScript?](http://stackoverflow.com/questions/143747/is-it-possible-to-trigger-a-links-or-any-elements-click-event-through-javasc) – Colin Brock Jul 26 '12 at 15:36
  • Read this post: http://stackoverflow.com/q/902713/870729 – random_user_name Jul 26 '12 at 15:37

1 Answers1

2

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • What if the `href` is relative to the current page? Will `window.location.href = "/index.php";` still work? – Cyrille Jan 15 '13 at 09:10