5

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

Clay
  • 4,700
  • 3
  • 33
  • 49
TJ Sherrill
  • 2,465
  • 7
  • 50
  • 88
  • 2
    Is it a typo in the post, or your code? `tigger` should be `trigger`. Unless you want a tiger bouncing up and down on your page. – John Koerner Jan 29 '13 at 04:54
  • Possible duplicate of [How to trigger click on page load?](http://stackoverflow.com/questions/2060019/how-to-trigger-click-on-page-load) – Atif Tariq Mar 08 '16 at 10:45

3 Answers3

3

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/

qbantek
  • 685
  • 12
  • 32
  • Clicks aren't actually followed to their href when using jQuery, likely a security concern. This demo only works in theory by doing the alert in the click handler. – rockerest Jan 29 '13 at 04:59
1

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();

Community
  • 1
  • 1
rockerest
  • 10,412
  • 3
  • 37
  • 67
0

The click handler that you are trying to trigger is most likely also attached via $(document).ready(). What is probably happening is that you are triggering the event before the handler is attached. The solution is to use setTimeout:

$("document").ready(function() {
setTimeout(function() {
    $("#link_to_content").trigger('click');
},10);
});

A delay of 10ms will cause the function to run immediately after all the $(document).ready() handlers have been called.

OR

use trigger in call back function of .load();

you can also use .on() instead of trigger()

$('div_to_load').load("#link_to_content",function(){
$("#link_to_content").trigger('click');
});

.on() example

$('div_to_click').on("click",".title",function(){
alert('sdfdsf');
});
shefali
  • 85
  • 1
  • 9