How to trigger click on page load?

JavascriptJquery

Javascript Problem Overview


I'm looking for a way to automatically "click" an item when the page loads.

I've tried using

$("document").ready(function() {
    $("ul.galleria li:first-child img").trigger('click');
});

but it doesn't seem to work? However, when I enter $("ul.galleria li:first-child img").trigger('click'); into Firebug's console and run the script, it works.

Can the trigger event be used on load?

Javascript Solutions


Solution 1 - Javascript

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() {
        $("ul.galleria li:first-child img").trigger('click');
    },10);
});

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

OR you check if the element is ready:

$("document").ready(function() {
  $("ul.galleria li:first-child img").ready(function() {
    $(this).click();
  });    
});

Solution 2 - Javascript

$(function(){

    $(selector).click();

});

Solution 3 - Javascript

$("document").ready({
    $("ul.galleria li:first-child img").click(function(){alert('i work click triggered'});
}); 

$("document").ready(function() { 
    $("ul.galleria li:first-child img").trigger('click'); 
}); 

just make sure the click handler is added prior to the trigger event in the call stack sequence.

  $("document").ready(function() { 
        $("ul.galleria li:first-child img").trigger('click'); 
    }); 

   $("document").ready({
        $("ul.galleria li:first-child img").click(function(){alert('i fail click triggered'});
    }); 

Solution 4 - Javascript

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

Solution 5 - Javascript

try this,

$("document").ready(function(){
 
$("your id here").trigger("click");
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustineView Question on Stackoverflow
Solution 1 - JavascriptnoahView Answer on Stackoverflow
Solution 2 - JavascriptStevenView Answer on Stackoverflow
Solution 3 - JavascriptMark SchultheissView Answer on Stackoverflow
Solution 4 - JavascriptKrish BhanushaliView Answer on Stackoverflow
Solution 5 - JavascriptAnkit KashniaView Answer on Stackoverflow