Huahua Wanwan
Huahua Wanwan

Reputation: 3

How to simulate a click event when document onready?

The two method below are not working for me; I need the button click event to fire with the document onready event. (#usrpost is a button element.)

$(function() {
   $("#usrpost").trigger("click");
   $("#usrpost").live("click",function() {
       //do something.
    });
});

I've also tried the following:

$(function() {
   $("#usrpost")[0].click();
   $("#usrpost").live("click",function() {
       //do something.
    });
});

Upvotes: 0

Views: 62

Answers (4)

vmontanheiro
vmontanheiro

Reputation: 1039

You can trigger the event too

$("#usrpost").trigger("click");

Upvotes: 0

Chris Wheeler
Chris Wheeler

Reputation: 1726

You must call the .click() after bind the event:

$(function() {
   $("#usrpost").live("click",function() {
       //do something.
   });
   $("#usrpost")[0].click();
});

.live() is also now deprecated in favour of .on():

$(function() {
   $('body').on('click', "#usrpost", function() {
       //do something.
   });
   $("#usrpost")[0].click();
});

Upvotes: 0

progsource
progsource

Reputation: 639

$(function() {
    $("#usrpost").on("click", function() {
        //do something.
    });
    $("#usrpost").click();
});

You had a typo in "function"

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388346

You need to trigger the event after the handler is added(apart from the spelling issue, also assuming you are using jQuery < 1.9)

$(function () {

    $("#usrpost").live("click", function () {

        //do something.
    });
    //fire it after the handler is added
    $("#usrpost").click();

});

Note: If you are using jQuery >= 1.7 use .on() instead of .live()

Upvotes: 1

Related Questions