Search code examples
javascriptprototypejs

prototype - simulate click on <a> tag


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.


Solution

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