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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With