views:

137

answers:

3

How do I javascript automatically click on a hyperlink (id is link_page) after 5 minutes?

+2  A: 

doing a click in js is pretty easy:

function clickTheLink() {
    var a = document.getElementById('link_page');
    a.click();
}

you can register a startup script from server code in c#:

string script = "setTimeout(clickTheLink, 5*60*1000);";
Page.ClientScript.RegisterStartupScript(typeof(Page), "5min", script, true);

this appends a script block to the end of your html. setTimeout executes the function provided after the delay specified. delay is in ms, so 5 mins times 60 seconds * 1000 milliseconds.

lincolnk
+2  A: 

If you want to trigger the onclick event handler of that link, it could work like this:

<head>
    <script type="text/javascript">
    setTimeout(function() {
        document.getElementById('link_page').onclick();
    }, 5 * 60 * 1000);
    </script>
</head>
...
<body>
    <a id="link_page" onclick="alert('test')">Test</a>
</body>

If you want to change to the location of the link after 5 minutes, you could try:

<head>
    <script type="text/javascript">
    setTimeout(function() {
        var linkUrl = document.getElementById('link_page').href;
        location.href = linkUrl;
    }, 5 * 60 * 1000);
    </script>
</head>
...
<body>
    <a id="link_page" href="http://www.google.de/"&gt;Test&lt;/a&gt;
</body>

The key function in both methods is the setTimeout() function, which takes a callback function and a timespan in milliseconds after which the callback function is executed. More on setTimeout(): http://www.w3schools.com/js/js_timing.asp

Mind: I tested these on OSX / Firefox, so test these on PC, too.

Max
don't call onclick, that won't call listeners added with addEventListener, just call click(), which simulates a user click
Juan Mendes
A: 

window.onload = function () { setTimeout('document.getElementById("link_page").click()', 1000*60*5); };

?

dalazx
ew. eval is evil, man. haven't use heard? `setTimeout(String)` will eval() the String.
David Murdoch