473,238 Members | 1,829 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,238 software developers and data experts.

Programatically trigger an onClick event?

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

Jul 23 '05 #1
17 61365
Mike Gratee wrote:
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();

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.
Jul 23 '05 #2
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" <be************@dimedia.hr> wrote in message
news:cd**********@ls219.htnet.hr...
Mike Gratee wrote:
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();

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.

Jul 23 '05 #3
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

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.
Jul 23 '05 #4
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" <be************@dimedia.hr> wrote in message
news:cd**********@ls219.htnet.hr...
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

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.

Jul 23 '05 #5
"Mike Gratee" <no****@me.org> writes:

A previous poster wrote:
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
<layer> elements and <div> elements with CSS position:absolute.
What versions of Netscape and Opera started supporting
getElementById?


Netscape: version 6 (after basing it on the Mozilla project).
Opera: version 4
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
"Berislav Lopac" <be************@dimedia.hr> wrote in message news:<cd**********@ls219.htnet.hr>...
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:

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.
Jul 23 '05 #7
Henry Lafleur wrote:
"Berislav Lopac" <be************@dimedia.hr> wrote in message news:<cd**********@ls219.htnet.hr>...
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:

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.

--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ - http://jibbering.com/faq

Jul 23 '05 #8
"Berislav Lopac" <be************@dimedia.hr> wrote in message news:<cd**********@ls219.htnet.hr>...
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


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.
Jul 23 '05 #9
Lasse Reichstein Nielsen wrote:
"Mike Gratee" <no****@me.org> writes:
> 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
Jul 23 '05 #10
Henry Lafleur wrote:
"Berislav Lopac" <be************@dimedia.hr> wrote in message news:<cd**********@ls219.htnet.hr>...
Please do not write attribution novels. Duplicating header information
of second-level interest is a waste of bandwidth and makes discussions
less legible.
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?
[...]


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

<http://netmeister.org/news/learn2quote.html>
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
Jul 23 '05 #11
On Sun, 18 Jul 2004 02:46:12 +0200, Thomas 'PointedEars' Lahn
<Po*********@nurfuerspam.de> wrote:

The latest version ist Firefox 0.9.1.


The latest version is Firefox 0.9.2.

Jul 23 '05 #12
Frederic Banaszak wrote:
On Sun, 18 Jul 2004 02:46:12 +0200, Thomas 'PointedEars' Lahn
<Po*********@nurfuerspam.de> wrote:


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


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
Jul 23 '05 #13
On Sun, 18 Jul 2004 14:55:15 +0200, Thomas 'PointedEars' Lahn
<Po*********@nurfuerspam.de> wrote:

Please do not write attribution novels. Reasons have been pointed out
before.

I have not written any novel, attribution or otherwise. My newsreader
does what it does. Since you are the only person ever, in all my years
on Usenet, to complain about such a thing, I really do not think that
I will be changing it any time soon.

The latest version ist Firefox 0.9.1.


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.


I stand corrected, I suppose, but since you are such a stickler for
precision, with one glaring exception, I thought that it should be
mentioned that a 0.9.2 version does exist (for Windows).

Jul 23 '05 #14
JRS: In article <40**************@PointedEars.de>, seen in
news:comp.lang.javascript, Thomas 'PointedEars' Lahn
<Po*********@nurfuerspam.de> posted at Sun, 18 Jul 2004 14:55:15 :
Frederic Banaszak wrote:
On Sun, 18 Jul 2004 02:46:12 +0200, Thomas 'PointedEars' Lahn
<Po*********@nurfuerspam.de> wrote:


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/...article-13.txt
http://www.ietf.org/internet-drafts/...-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?

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME ©
Web <URL:http://www.uwasa.fi/~ts/http/tsfaq.html> -> Timo Salmi: Usenet Q&A.
Web <URL:http://www.merlyn.demon.co.uk/news-use.htm> : about usage of News.
No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News.
Jul 23 '05 #15
Grant Wagner <gw*****@agricoreunited.com> wrote in message news:<40***************@agricoreunited.com>...
Henry Lafleur wrote:
"Berislav Lopac" <be************@dimedia.hr> wrote in message news:<cd**********@ls219.htnet.hr>...
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.
Jul 23 '05 #16
Lasse Reichstein Nielsen wrote:
"Mike Gratee" <no****@me.org> writes:

A previous poster wrote:
> var link = document.getElementById['yourLinksIdAttrbuteValue'];


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


Duh! A typo.

Berislav

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.
Jul 23 '05 #17
Henry Lafleur wrote:
"Berislav Lopac" <be************@dimedia.hr> wrote in message
news:<cd**********@ls219.htnet.hr>...
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:

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

--
If the Internet is a Marx Brothers movie, and Web, e-mail, and IRC are
Groucho, Chico, and Harpo, then Usenet is Zeppo.
Jul 23 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Nick72 | last post by:
Hi, I've been reading through tons of posts regarding the problems people have encountered with getting javascript functions to trigger when called from onclick events... But so far, I haven't...
1
by: Dark Magician | last post by:
Comrades: Am trying to build a UI widget. I'm sure part of the problem is proper variable scope or object reference, and part of the problem may be the way I'm calling the function, but, here...
17
by: abs | last post by:
My element: <span onclick="alert('test')" id="mySpan">test</span> Let's say that I don't know what is in this span's onclick event. Is it possible to add another action to this element's onclick...
1
by: Hrvoje Vrbanc | last post by:
Hello all! My question is the following: I add buttons (server controls) programatically into a table cell. Example: Dim btObnovi As Button = New Button() celija25.Controls.Add(btObnovi) ...
2
by: Richard Morse | last post by:
Hi! I have an aspx that I've created which has an asp:Button in it. I would like to be able to change the OnClick handler at runtime (basically, I want this form to either edit or create a...
3
by: Glenn | last post by:
I've got a datalist that includes in each databound row a button to delete that specific record. But for some reason, clicking the button does not trigger the event handler. here's the datalist ...
5
by: Stuart Shay | last post by:
Hello All I am working on ASP.NET 1.1 Custom Pager that allows a User to Enter a Number in a TextBox and go to the page selected. Since the OnClick Event does not work in ASP.NET 1.1 for a...
2
by: =?Utf-8?B?Uml0YUc=?= | last post by:
I posted this question in the C# discussion group but am posting it here also since ASP is involved. I'm new to C# and need some help regarding an onClick event not firing. I have a data grid...
3
by: Dreea | last post by:
Hello I have designed a control that consists of a textarea and a button. When the user writes text in the textarea and the Enter key is pressed then the onClick event of the button is triggered....
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.