Forum Moderators: open

Message Too Old, No Replies

Programmatically clicking on a link

click() function not available

         

waldemar

10:49 am on Aug 12, 2006 (gmt 0)

10+ Year Member



Hello there,

I am trying to write a bookmarklet for some tasks in a cms that is using javascript heavily.
In order to create one of the desired functions I need to programmatically click on a link.

<a href="blabla" id="mylink">mylink</a>

---> document.getElementById('mylink').click();

doesnt work. Obviously the link object does not support this function.
I can not change the link to a button or similar. Also I cant just change the document.location because the link activates some further javascript functionality. Does anyone have an idea to be able to activate that link?

With best regards
Waldemar

daveVk

12:15 pm on Aug 12, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



think click() is IE specific. try

eval( document.getElementById('mylink').href );

waldemar

2:23 pm on Aug 12, 2006 (gmt 0)

10+ Year Member



Hey dave,

thanks, but it didnt do the trick. I tried:


<BODY onload="test();">
<a href="http://www.webmasterworld.com" id="mylink">Link</a>

<script type="text/javascript">
function test()
{
alert("function called");
eval ( document.getElementById('mylink').href );
}
</script>
</BODY>

and get this error:


Error: syntax error
Line: 18, Column: 29
Source Code:
[webmasterworld.com...]

--> error kind of makes sense to me, as I am trying to execute an URL with this... ;)

daveVk

1:44 am on Aug 13, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry was assuming you had javascipt in href of link. You may need to check href, if http: assign to document.location. Depending how general a solution you need you may also need to consider target= and other protocols https, ftp etc, also onclick=. Anyone have a more general solution?

supermoi

3:22 pm on Aug 13, 2006 (gmt 0)

10+ Year Member



I think what you're looking for is onclick, and not click.

document.getElementById(id).onclick = name_of_function;
or
document.getElementById(id).attachEvent('onclick',name_of_function); (for IE)
document.getElementById(id).addEventListener('click',name_of_function,false); (for others)

RonPK

4:13 pm on Aug 13, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You say that "the link activates some further javascript functionality". Can't you let the bookmarklet trigger the same functionality?