Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click link on load with jQuery

Tags:

jquery

onload

Here's a contrived example of my code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>    
        <title></title>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
        <link rel="stylesheet" type="text/css" href=".css"/>
    </head>
    <body>
        <div>
            <a href="http://www.google.com" class="foo">YahOO</a>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
       <script type="text/javascript">
            $("document").ready(function() {
                $("#foo").trigger('click');
            });
        </script>
    </body>
</html>

I would like to have the link fired immediately upon page load. The above does not work and is incorrect? How could this be done?

like image 297
Paul Avatar asked Apr 03 '12 19:04

Paul


People also ask

How to trigger a click on a link using jQuery?

on("click", "a", function(){ $(this). text("It works!"); }); $(document). ready(function(){ $("a"). trigger("click"); });

How can call Click event on page load in jQuery?

Just use the setTimeout() method in jquery. It will call a click function without clicking it.

What is trigger method in jQuery?

The trigger() method is a method in jQuery which is used to trigger a specified event handler on selected element. Syntax: $(selector).trigger(event, param1, param2) Note: Extra parameters can be passed in trigger() method. Example 1: This method triggered two methods to increase the value of method.

How do you click a button in JQ?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


2 Answers

You have the class foo set on your element, not an id so you need to use .foo. Also, as @JusticeErolin pointed out, the document ready handler doesn't need quotes. Try this:

$(document).ready(function() {
    $(".foo").trigger('click');
});

For reference, $("#foo") will look for an element with id="foo", of which there should only ever be one in your page as ids should be unique.

$(".foo") will look for elements with class="foo", of which you can have as many as you like.

like image 147
Rory McCrossan Avatar answered Sep 23 '22 12:09

Rory McCrossan


I tried many options, but I found one option which worked for me :

$(document).ready(function(){ 
     $('#upload-file')[0].click(function(){
     }); 
});
like image 41
Irshad Khan Avatar answered Sep 24 '22 12:09

Irshad Khan