Programatically trigger an onClick event?

M

Mike Gratee

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
 
B

Berislav Lopac

Mike said:
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?

var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();
 
M

Mike Gratee

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

Berislav Lopac said:
Mike said:
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?

var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();
 
B

Berislav Lopac

Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?

Berislav
 
M

Mike Gratee

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

Berislav Lopac said:
Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?

Berislav
 
L

Lasse Reichstein Nielsen

var link = document.getElementById['yourLinksIdAttrbuteValue'];

That should be:
var link = document.getElementById('yourLinksIdAttrbuteValue');
getElementById is a function, not an array.
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?

Netscape 4 had document.layers, a collection which only contains
What versions of Netscape and Opera started supporting
getElementById?

Netscape: version 6 (after basing it on the Mozilla project).
Opera: version 4
 
H

Henry Lafleur

Berislav Lopac said:
Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?

Berislav

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

Grant Wagner

Henry said:
Berislav Lopac said:
Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?

Berislav

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.

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

Henry Lafleur

Berislav Lopac said:
Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?

Berislav

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

Thomas 'PointedEars' Lahn

Lasse said:
Mike Gratee said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];

That should be:
var link = document.getElementById('yourLinksIdAttrbuteValue');
getElementById is a function, not an array.

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
 
T

Thomas 'PointedEars' Lahn

Henry said:
"Berislav Lopac" <[email protected]> wrote in message news:<[email protected]>...

Please do not write attribution novels. Duplicating header information
of second-level interest is a waste of bandwidth and makes discussions
less legible.
Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?
[...]

Please quote only what you are referring to. Explicitely
*do not* quote signatures if you are not referring to them.

It does not work with FireFox 9.1 (latest) [...]

The latest version ist Firefox 0.9.1.
which runs Mozilla Gecko engine:

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:
Error: lnkNode.click is not a function
Source File: http://blah/WebApplication1/TreeNode.js
Line: 250

Works fine in IE.

Searching for an answer...

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
 
T

Thomas 'PointedEars' Lahn

Please do not write attribution novels. Reasons have been pointed out
before.
The latest version is Firefox 0.9.2.

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
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Thomas 'PointedEars' Lahn
Please do not write attribution novels. Reasons have been pointed out
before.

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

Henry Lafleur

Grant Wagner said:
Henry said:
Berislav Lopac said:
Mike Gratee wrote:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes, what
exactly happens?

Berislav

It does not work with FireFox 9.1 (latest) which runs Mozilla Gecko engine:
...
Henry.

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,

The only issues here are that this:
if (link.onclick && link.onclick()) {

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) {
if (link.target) {
....

or maybe (keeping with the terse code):

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

which makes me want to say, "Yikes!"

Another small issue is:
window.location.href = link.href;

would not honor the <base target=... setting. This may need to read:
if (link.target) {
window.open(link.href, link.target);
} else {
! 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 {
window.location.href = link.href; ! }
}

or (eliminating redundancy some):

! if (!link.onclick || link.onclick && link.onclick())
! var strTarget = null;
! var elesBase;
if (link.target) {
! 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 {
window.location.href = link.href;
! }
! }


This makes the code much uglier, but more robust.
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.

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

Berislav Lopac

Henry said:
Berislav Lopac said:
Mike said:
var link = document.getElementById['yourLinksIdAttrbuteValue'];
link.click();

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?

Have you tried? If not, why do you think if it won't work? If yes,
what exactly happens?

Berislav

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

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top