John
John

Reputation: 10156

Jquery running when page loads and when button clicked

If a person went to my page I want some jquery to run, then if they click a button on the page I want the same jquery code to run. Do I have to create seperate functions for this? One that loads when the person comes to the page and then the click function when someone clicks the button? Or for the sake of not having to duplicate code can it all be in one function?

Upvotes: 1

Views: 2378

Answers (3)

user113716
user113716

Reputation: 322562

You can reuse the function for both:

$(function() {

       // declare the function
    function myReusableFunction() {
           // do something extraordinary
    }

    // call it on page load
    myReusableFunction();

    // assign to handler
    $('button').click( myReusableFunction );
});

Note that the value of this and the parameter (if any) will be different.

If that's an issue, you can just call it directly by chaining a click trigger.

$(function() {

    // assign to handler AND call it
    $('button').click( function() {
           // do something extraordinary
    }).click();
});

EDIT: If there's more than one button that it is assigned to, the .click() will trigger for all of them.

If this isn't what is desired, you could change it to:

$(function() {

    // assign to handler AND call it
    $('button').click( function() {
           // do something extraordinary
    }).eq(0).click();
});

...to trigger it only on the first one.

Or this:

$(function() {

    // assign to handler AND call it
    $('button').click( function() {
           // do something extraordinary
    }).triggerHandler( 'click' );
});

...which only fires on the first element, but also has a couple other differences. See the docs for triggerHandler for more.

Upvotes: 4

amosrivera
amosrivera

Reputation: 26524

$(function() {

    $("#myButton").click(function() {
        //your code
        alert("exeuted"); //on click button alerts
    }).click(); //simulate click to execute onload

});

Online demo here: http://jsfiddle.net/nMPMt/

Upvotes: 1

Jason Benson
Jason Benson

Reputation: 3399

Here's an example that will bind an event, and additionally fire it.

$(function() {
    $('#yourButton').click(function(){
       alert('Yay');
    }).click();

});

Edit: cleaned up my explanation and horrid grammar...

Upvotes: 0

Related Questions