Question

I'm trying to trigger a click on a link when a page loads via ajax call, I tried all methods I found, but I can't manage to do that.

Considering that the link on which I want to trigger the click is given by this code

<a href="download.php?file=cloud/index.html" target="_blank" id="cliccami">Click here</a>

Here are the codes that I tried

<script> $("#cliccami").trigger("click"); </script>
<script> $("#cliccami")[0].click(); </script>
<script> window.open($("#cliccami").attr("href"), "_blank"); </script>

Both script and element are in the page loaded via ajax call. Could anyone help me to find out what's the matter?

Was it helpful?

Solution

EDIT, I think this is what you're looking for:

html:

<a href="http://www.google.com" target="_blank" id="cliccami">Click here</a>

jQuery:

$(document).ready(function() {

    $('#cliccami').click(function(e) {
        window.open($(this).attr('href'));
        e.preventDefault();
    });

    $('#cliccami').click();
});

In my example (JSFiddle: http://jsfiddle.net/qw9BW/) #cliccami's click event is captured, alerted, then stopped. then a $.click() is ran on page load to force the click event to happen.

OTHER TIPS

Have you tried using a ready function?

$(document).ready(function() {
   $("#cliccami").trigger("click");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top