001
001

Reputation: 65147

Javascript to auto click on hyperlink

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

Upvotes: 1

Views: 6907

Answers (3)

dalazx
dalazx

Reputation: 11

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

?

Upvotes: 1

BMBM
BMBM

Reputation: 16013

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/">Test</a>
</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.

Upvotes: 3

lincolnk
lincolnk

Reputation: 11238

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.

Upvotes: 4

Related Questions