views:

92

answers:

2

How do i simulate a click on an anchor (<a>) tag in prototype?

for example i would expect the below code to work in that clicking the 2nd link ("click me") would cause the alert('here'); to be executed.

<a id="myLink" href="" onclick="alert('here'); return false;">don't click me</a>
<br />
<a href="" onclick="$('myLink').click(); return false;">click me</a>

thanks, p.

+1  A: 

You can use the simulate() method from the Protolicious library:

You can see the test sandbox here, but with events added:

<a id="myLink" href="#">don't click me</a>
<br />
<a id="clicked" href="#">click me</a>

<script type="text/javascript">
Event.observe($('myLink'), 'click', function () { alert ('aaa'); return false; });
Event.observe($('clicked'), 'click', function () { alert ('bbb'); $('myLink').simulate('click'); return false; });
</script>
Bogdan Constantinescu
have you tried to run the code? because i think the problem might be that $('myLink') is not returning the HTMLElement object. It doesn't for me anyway...
pstanton
Check out the revised answer with an example page :)
Bogdan Constantinescu
ah i see .. i need protolicious ... but surely there's a way in prototype without a 3rd party lib? thanks for the info .. at least i know there's a way. will hold out a little in case someone else has a prototype only answer.
pstanton
A: 

I haven't tested it, but try this:

<a id="myLink" href="" onclick="alert('here'); return false;">don't click me</a>
<br />
<a href="" onclick="Event.fire($('myLink'), 'click');">click me</a>
Ash White
this doesn't work.
pstanton
Oops, I forgot that Prototype Events are limited to custom events. Can I ask why you cant to simulate a click event? Chances are there's a better way to approach it.
Ash White
because this other link has had a bunch of event listeners registered to it by a third party program. it would be easier to use the other link as a registry of sorts rather than plumb together all the event handlers on the link that actually gets clicked.
pstanton