Willy
Willy

Reputation: 763

Auto-execute javascript functions AND call them later?

I read on many places that you can auto launch js functions on load by doing :

$(function() {
    // code...
});

Or

var myFunc = function() {
   // code...
}();

My question is, how do you call these functions later ? Because the simple declaration

function myFunc() {
    // code...
}

can be easily recalled but doesn't auto-launch. I have to manually call them all on load, and that's annoying, take up spaces in the code and it can be an error source if i forgot one.

If you don't understand my explanations, here's an example :

I have a "weight" and a "height" field in my form, and i need to calculate the BMI (Body Mass Index). When the page loads, the weight and height are filled by the database, then i launch the calculation when everything's ready. But later, if the user changes the weight or the height, the BMI have to recalculate immediately. What's the best way to do that ? Using jquery or pure JS, I don't mind.

Thanks.

Upvotes: 26

Views: 70698

Answers (1)

Joseph
Joseph

Reputation: 119847

A reusable immediate function

var reference = (function thename(){

    //function body

    return thename; //return the function itself to reference

}()); //auto-run


reference(); //call it again
reference(); //and again

Note that calling the function returns a reference to the function you just called.

var anotherReference = reference(); //anotherReference === reference

Upvotes: 49

Related Questions