Automatically call a function via Javascript?

When someone enters something into a textbox on the html page, he then taps on the Save button to call a function to save it to localStorage. He also taps on Load to populate the page’s fields the next time he is on that page:

{ SAVE } { LOAD }

[ textbox ] [ textbox ]

[ textbox ] [ textbox ]

Is there a way to automatically call a function via Javascript so I can do away with the Save and Load buttons?

I suppose the script would wait two seconds for the body to load completely (or a function could be called near the end of </body>, thus loading the fields just once for that page - I tested this just now and that works!

Then maybe the saving would be prompted by detecting a full second of lag time after a keystroke. This latter part I don’t understand how to achieve. I don’t know if the saving should be in response to a lag time after a keystroke, or just a timed interval every X seconds.

What kind of code should I be looking for? What syntax terms do I need to look up? Is this hard to do for someone who isn’t thoroughly familiar with Javascript?

For the load you can use the ‘onload’ event handler. It is triggered when the page has finished loading.


window.onload = function() {
    // do stuff to load your form fields
};

Or, if you’re using jquery:


$(function() {
    // do stuff to load your form fields
});

The save button is a little trickier. When exactly should the saving code be triggered which is now called by the save button?

I want the save code to trigger before the user leaves the page, which, since there is no Save button, can happen at any time. So I thought perhaps it should save 1 second after it detects a keyboard input in any field. If there is a series of inputs less than a second apart, then it can wait until a full second passes with no keystrokes, then save.

I see there is a timer function. It looks like I need to detect a keystroke, start the timer, then restart the timer when it detects a keystroke before the timer finished.

Since I have over 200 fields, it would be awkward to have to id each field and repeat the code 200 times!

Thanks for the help on the Load.

I am using JQuery. Will the onload button work for all the div pages? I don’t see it happening here in Google.