Programatically trigger an onClick event?

Discussion in 'Javascript' started by Mike Gratee, Jul 15, 2004.

  1. Mike Gratee

    Mike Gratee Guest

    Is it possible to use JavaScript to cause the browser to click a link on a
    page and have the browser act exactly like the user had clicked on the link

    In other words, I need to programmatically issue a JavaScript statement
    which causes the browser to act just like the user clicked on a link in my
    page. And if that link has an onClick JS event defined, I'd want that
    onClick event to execute too, exactly the same as if the user actually
    clicked on the link.

    I know you may be thinking that I should just call the onClick event for the
    link directly rather than trying to simulate a click using JavaScript.
    However this is not sufficient. In my case I need to use JS to cause the
    browser to click a link just like the user had clicked it, have any
    corresponding events that may be defined fire (such as onClick), and then
    have the browser follow the href for the link to its appropriate
    target/page. Think of it as a macro-like operation I am trying to do
    whereby I am simulating an action of and end user that is clicking a link.

    Can someone let me know if this is possible, and if so, how? I need it to
    work with IE 5 and higher, and the later versions of Netscape/Opera/Mozilla
    if possible.

    I'm thinking that someone I may be able to access the properties of an href
    tag programmatically and call a method on it to simulate a real click. Any
    code samples or snippets would be MUCH appreciated.


    ** Mike
    Mike Gratee, Jul 15, 2004
    1. Advertisements

  2. var link = document.getElementById['yourLinksIdAttrbuteValue'];;
    Berislav Lopac, Jul 15, 2004
    1. Advertisements

  3. Mike Gratee

    Mike Gratee Guest

    Great - thanks alot. However I don't think that will work with Netscape 6,
    Mozilla or Opera right? How would I change it to work with those?


    Mike Gratee, Jul 16, 2004
  4. Have you tried? If not, why do you think if it won't work? If yes, what
    exactly happens?

    Berislav Lopac, Jul 16, 2004
  5. Mike Gratee

    Mike Gratee Guest

    I was under the impression that getElementById would not work like this with
    some of the older browsers. Wasn't there a different approach to getting to
    an element under older versions of Netscape and Opera? What is that
    approach? What versions of Netscape and Opera started supporting
    getElementById? Thank you!


    Mike Gratee, Jul 16, 2004
  6. That should be:
    var link = document.getElementById('yourLinksIdAttrbuteValue');
    getElementById is a function, not an array.
    Netscape 4 had document.layers, a collection which only contains
    Netscape: version 6 (after basing it on the Mozilla project).
    Opera: version 4
    Lasse Reichstein Nielsen, Jul 16, 2004
  7. It does not work with FireFox 9.1 (latest) which runs Mozilla Gecko engine:

    Error: is not a function
    Source File: http://blah/WebApplication1/TreeNode.js
    Line: 250

    Works fine in IE.

    Searching for an answer...

    Henry Lafleur, Jul 16, 2004
  8. Mike Gratee

    Grant Wagner Guest

    This might work for you:

    <a href="" onclick="alert('hi');return true;">Yahoo!</a>
    <input type="button" onclick="navigateLink(0);" value="Click link index 0">
    <script type="text/javascript">
    function navigateLink(linkIndex) {
    var link = document.links[linkIndex];
    if (link.onclick && link.onclick()) {
    if ( {,;
    } else {
    window.location.href = link.href;

    Of course it won't completely mimic the user clicking the link, if the link has a target and Javascript
    is disabled, a user-initiated click would still open a new window (assuming that TARGET attributes are
    honored by the user agent). Also, a TARGET attribute probably has a better chance of opening a new
    window then does, given the current state of popup blockers.
    Grant Wagner, Jul 16, 2004
  9. Here's a solution (should handle IE and Netscape 6+/Mozilla

    * Emulate the IE method.
    * plnkNode - The link object to emulate the click on.
    function MozillaLinkClick(plnkNode)
    // Emulate click on Mozilla
    var bolFollowLink = true;
    var strTarget = null;

    // Run the link onClick event.
    if (plnkNode.onclick)
    if (plnkNode.onclick() == false)
    bolFollowLink = false;

    // Get the link target.
    if (
    strTarget =;
    if (bolFollowLink)
    if (strTarget == null)
    // Open using the default target if not set on the link.;
    } else {
    // Open using the link target., strTarget);

    // Assume a link object called Link:
    if (;

    Note that under normal behavior if the onClick event returns false,
    the link should not be followed.

    Henry Lafleur, Jul 16, 2004
  10. The proper correction would have been: "getElementById() is a method,
    not a non-function property." ECMAScript/J(ava)Script has no concept
    of associative arrays, the above referencing would be used as bracket
    property accessor on *any* object.

    Thomas 'PointedEars' Lahn, Jul 18, 2004
  11. Please do not write attribution novels. Duplicating header information
    of second-level interest is a waste of bandwidth and makes discussions
    less legible.
    Please quote only what you are referring to. Explicitely
    *do not* quote signatures if you are not referring to them.

    The latest version ist Firefox 0.9.1.
    Firefox uses the Netscape Gecko engine. But Gecko is a *rendering*
    engine, not a script engine. The script engine used in Mozilla/5.0
    user agents is SpiderMonkey, a JavaScript 1.5 engine written in C++.
    It is this engine which puts messages like the following to the
    JavaScript console:
    The answer is that Mozilla/5.0 and IE implement different Document
    Object Models (DOMs). Mozilla/5.0 implements the Gecko DOM, IE
    implements the IE DOM.


    An object or property of one DOM needs not to be available in another
    and apart of that, different UAs implement different scripting
    languages. This is why client-side scripting is much more challenging
    that it at first may seem and good scripts much more sophisticated than
    the usual copy & pray scripts may (and some even explicitely and falsely
    do) suggest.


    Thomas 'PointedEars' Lahn, Jul 18, 2004
  12. Please do not write attribution novels. Reasons have been pointed out
    With a branch/trunk release scheme for different operating systems and
    platforms as uses, it remains to be discussed what can be
    considered the latest version. For me, for example the latest version
    to date is Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8a3)
    Gecko/20040717 Firefox/0.9.1+, a GNU/Linux Nightly Build as of
    yesterday. The latest release is 0.9.2, but available as binary only
    for 32 bit Windows. The latest public binaries for GNU/Linux and MacOS
    X are of version 0.9.1.

    Thomas 'PointedEars' Lahn, Jul 18, 2004
  13. JRS: In article <>, seen in
    Thomas 'PointedEars' Lahn
    Incorrectly, which is possibly why people ignore your intolerant
    demands. AISB, you should read
    in order to learn current thinking on the subject.

    It is that it is acceptable to include poster's name, E-address, the
    newsgroup name, and the precursor article's date/time and message-ID.

    Many people find these helpful under various circumstances - one example
    is when someone such as yourself resurrects ancient threads without

    I have repeatedly pointed out to you, publicly, the unreasonableness of
    your demands. However, as you claim to have the anti-social habit of
    kill-filing those who disagree with you, you may not have seen all of

    The net effect, of course, is to make you appear a dictatorial, juvenile

    Have you noticed how rapidly the number of articles posted to this
    newsgroup per week has been dropping since you began to post?
    Dr John Stockton, Jul 18, 2004
  14. Grant,

    The only issues here are that this:
    would return false if there was no onclick event. The link would only
    be followed if it had an onclick event in this case. It may be better
    to use a variable here that is either true or the result of the

    ! var bolOnClick = true;
    ! if (link.onclick) bolOnClick = link.onclick();
    ! if (bolOnClick) {

    or maybe (keeping with the terse code):

    ! if (!link.onclick || link.onclick && link.onclick())

    which makes me want to say, "Yikes!"

    Another small issue is:
    would not honor the <base target=... setting. This may need to read:
    ! var strTarget = null;
    ! var elesBase;
    ! // Use the DOM to get the base (if available)
    ! if (document.getElementsByTagName) {
    ! elesBase = document.getElementsByTagName('base');
    ! if (elesBase.length > 0) {
    ! strTarget = elesBase[0].getAttribute('target');
    ! }
    ! }
    ! if (strTarget) {
    !, strTarget);
    ! } else {
    or (eliminating redundancy some):

    ! if (!link.onclick || link.onclick && link.onclick())
    ! var strTarget = null;
    ! var elesBase;
    ! strTarget =;
    ! } else {
    ! // Use the DOM to get the base (if available)
    ! if (document.getElementsByTagName) {
    ! elesBase = document.getElementsByTagName('base');
    ! if (elesBase.length > 0) {
    ! strTarget = elesBase[0].getAttribute('target');
    ! }
    ! }
    ! }
    ! if (strTarget) {
    !, strTarget);
    ! } else {
    ! }
    ! }

    This makes the code much uglier, but more robust.
    The popup blockers are a big pain for legit web developers. We use
    popups to clear concurrent licenses when the user closes the browser,
    so that may not work anymore (more a problem for our customers than
    for us). Especially since now IE will include popup blocking. (I can
    see the bugs in that streaming in!)

    Fortunately, most of the apps I write are for an intranet or a trusted
    internet site. This means we can set minimum browser requirements
    above what we can do for internet sites.

    Thanks for the feedback,

    Henry Lafleur, Jul 19, 2004
  15. Duh! A typo.

    Berislav Lopac, Jul 20, 2004
  16. Don't have the time to test it, but try this:

    //write this somewhere in the global scope of your script
    var links = document.getElementsByTagName('a');
    links[0] = function() { this.handleEvent('onclick'); }

    Berislav Lopac, Jul 20, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.