toni
toni

Reputation: 43

How to click a button element on page load

I have created 5 buttons. I'm loading some pages on button click. I want the first button automatically clicked on page load and load it's corresponding html file and the remaining buttons should load html files only on clicking them. Someone help me!!

This is my jquery:

$('a#Home').click(function() {
  $("#home").load("x.html");
});

$('a#Menu1').click(function() {
  $("#menu1").load("y.html");
});

$('a#Menu2').click(function() {
  $("#menu2").load("z.html");
});

$('a#Menu3').click(function() {
  $("#menu3").load("searcharray.html");
});

$('a#Menu4').click(function() {
  $("#menu4").load("sortarray.html");
});

Upvotes: 0

Views: 2916

Answers (5)

Therichpost
Therichpost

Reputation: 1815

You can try this:

 <script>
       function pageLoad()
{
    alert('hello');
}

pageLoad();

 </script>


<button id="btn1" onclick="pageLoad()">btn1</button>

Upvotes: 0

Deanmv
Deanmv

Reputation: 1211

Assuming the first button is Home then you want run that on document ready by using $(function()

<script>
    $(function() {
        $('a#Home').click();
    });

    function loadHome() {
        $("#home").load("x.html");
    };
</script>

Then update your link to be like:

<a id="Home" onclick="loadHome()">Click Me</a>

Upvotes: 0

Pankaj Sharma
Pankaj Sharma

Reputation: 236

Just test this code. I think this will help you.

$( document ).ready(function() {
    console.log( "ready!" );
    $('#btn1').trigger( "click" );
});
function fun1()
{
	alert('loaded');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="btn1" onclick="fun1()">btn1</button>
<button id="btn2">btn1</button>
<button id="btn3">btn1</button>
<button id="btn4">btn1</button>

Upvotes: 1

yarwest
yarwest

Reputation: 990

Theoretical answer

You can trigger any event on any element using the .trigger() method. This will require you to specify which event you want to fire. More information.

It is also possible to trigger a click event just by calling .click() after binding the event handling. The documentation shows us that we can use this function for both purposes.

$( document ).ready() is an interaction that can be used to run code once when the document has been loaded. More info on that can be found here.

Examples

Example #1 (using .trigger())

$( document ).ready(function() {
    $('a#Home').trigger('click');
});

Example #2 (using .click())

$( document ).ready(function() {
    $('a#Home').click();
});

Upvotes: 0

Sahal Tariq
Sahal Tariq

Reputation: 198

trigger the event yourself:

$('a#Home').click(function() {
  $("#home").load("x.html");
});
$('a#home').trigger('click');

Upvotes: 0

Related Questions