Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger Click as a page loads using jquery

I have seen a ton of posts about this, but none worked as I was trying to.

$(document).ready(function() {
   $('#link_to_content').tigger('click');
});

Once the page is loaded I want to trigger the click. I know its weird to open a link once a page loads but in this case it makes sense.

I am using jquery 1.7

like image 629
TJ Sherrill Avatar asked Oct 05 '22 05:10

TJ Sherrill


2 Answers

should be:

$(document).ready(function() {
   $('#link_to_content').trigger('click');
});

working example here: http://jsfiddle.net/zpnQv/

EDIT:

if you want to follow the link you could do something like:

HTML:
<a href="http://www.yahoo.com/" id="link_to_content">Click Me</a>


JS:
$(document).ready(function () {

    $("#link_to_content").click(function (e) {
        e.preventDefault();

        var href = $(this).attr("href");

        alert("going to " + href);
        window.location = href;
    });
    $('#link_to_content').trigger('click');
});

Example: http://jsbin.com/omudih/1/

like image 83
qbantek Avatar answered Oct 07 '22 18:10

qbantek


jQuery won't click on links. My own interpretation is that this is a bit of a security risk, which is more or less what the linked answer boils down to.

However, as the linked answer states, you can simply select the Javascript HtmlDOMElement and .click() it.

In other words: $('#link_to_content')[0].click();

like image 36
rockerest Avatar answered Oct 07 '22 18:10

rockerest