Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger click on page load?

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?

like image 389
Justine Avatar asked Jan 13 '10 20:01

Justine


People also ask

How do you trigger onload?

Yeah, you can use a click event called onLoad() . Just use the setTimeout() method in jquery. It will call a click function without clicking it.

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How to fire click event on page load in jQuery?

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

Which event will be triggered automatically after the page gets loaded in the browser?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

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();   });     }); 
like image 124
noah Avatar answered Oct 10 '22 08:10

noah


$(function(){      $(selector).click();  }); 
like image 35
Steven Avatar answered Oct 10 '22 07:10

Steven