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
    directly?

    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.

    Thanks!!

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

  2. var link = document.getElementById['yourLinksIdAttrbuteValue'];
    link.click();
     
    Berislav Lopac, Jul 15, 2004
    #2
    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

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

    Berislav
     
    Berislav Lopac, Jul 16, 2004
    #4
  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

     
    Mike Gratee, Jul 16, 2004
    #5
  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
    #6
  7. It does not work with FireFox 9.1 (latest) which runs Mozilla Gecko engine:

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

    Works fine in IE.

    Searching for an answer...


    Henry.
     
    Henry Lafleur, Jul 16, 2004
    #7
  8. Mike Gratee

    Grant Wagner Guest

    This might work for you:

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

    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 window.open() does, given the current state of popup blockers.
     
    Grant Wagner, Jul 16, 2004
    #8
  9. Here's a solution (should handle IE and Netscape 6+/Mozilla
    1.2/FireFox):

    /**
    * Emulate the IE link.click 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 (plnkNode.target)
    {
    strTarget = plnkNode.target;
    }
    if (bolFollowLink)
    {
    if (strTarget == null)
    {
    // Open using the default target if not set on the link.
    window.open(plnkNode.href);
    } else {
    // Open using the link target.
    window.open(plnkNode.href, strTarget);
    }
    }
    }

    // Assume a link object called Link:
    if (Link.click)
    Link.click();
    else
    MozillaLinkClick(Link);


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

    Henry.
     
    Henry Lafleur, Jul 16, 2004
    #9
  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.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Jul 18, 2004
    #10
  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.

    <http://www.mozilla.org/docs/dom/>
    <http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_reference_entry.asp>

    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.

    <http://pointedears.de/scripts/test/whatami>


    PointedEars
     
    Thomas 'PointedEars' Lahn, Jul 18, 2004
    #11
  12. Please do not write attribution novels. Reasons have been pointed out
    before.
    With a branch/trunk release scheme for different operating systems and
    platforms as mozilla.org 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.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Jul 18, 2004
    #12
  13. JRS: In article <>, seen in
    Thomas 'PointedEars' Lahn
    Incorrectly, which is possibly why people ignore your intolerant
    demands. AISB, you should read
    http://www.ietf.org/internet-drafts/draft-ietf-usefor-article-13.txt
    http://www.ietf.org/internet-drafts/draft-ietf-usefor-useage-00.txt
    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
    warning

    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
    those.

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


    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
    #13
  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
    link.onclick().

    ! 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) {
    ! window.open(link.href, strTarget);
    ! } else {
    or (eliminating redundancy some):

    ! if (!link.onclick || link.onclick && link.onclick())
    ! var strTarget = null;
    ! var elesBase;
    ! strTarget = link.target;
    ! } 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) {
    ! window.open(link.href, 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.
     
    Henry Lafleur, Jul 19, 2004
    #14
  15. Duh! A typo.

    Berislav
     
    Berislav Lopac, Jul 20, 2004
    #15
  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].prototype.click = function() { this.handleEvent('onclick'); }

    Berislav
     
    Berislav Lopac, Jul 20, 2004
    #16
    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.