Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-execute javascript functions AND call them later?

Tags:

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.

like image 950
Willy Avatar asked May 22 '12 14:05

Willy


People also ask

How do you call a function after some time?

You can use JavaScript Timing Events to call function after certain interval of time: This shows the alert box every 3 seconds: setInterval(function(){alert("Hello")},3000); You can use two method of time event in javascript.

Does JavaScript execute automatically?

Many JavaScript-enhanced web pages have scripts that must be executed automatically when the page is loaded. A web page containing a "scrolling status bar message," for example, should be able to start scrolling the message immediately after the page has loaded, without user interaction.


1 Answers

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 
like image 187
Joseph Avatar answered Sep 21 '22 06:09

Joseph