1

I have to wrap my functions in a namespace. How do I run my function on page load in this format?

window.myFunction = { submitButton: function () {

document.getElementById('button').value='My text';

}
window.onload = submitButton;
};

If I write this without the namespace, it works fine

function submitButton() {     document.getElementById('button').value='My text'; }

window.onload = submitButton;
Spencer Pope
  • 455
  • 6
  • 23
  • I think his question is about how to get to submitButton not onload which he already have in his question – Neta Meta May 23 '16 at 15:03
  • Closer to a duplicate of: http://stackoverflow.com/q/1235985/1807040 also I think you meant. `window.init = window.myFunction.submitButton` – Saqib Rokadia May 23 '16 at 15:04
  • 1
    this piece of code is not formatted correctly. it does not execute like this because you are making an assignment to `window.onload` within an object body! – Dominic May 23 '16 at 15:04
  • Dominic you can assign function to onload. - thats what you should do actually. – Neta Meta May 23 '16 at 15:05
  • 1
    yes but you can't assign it while you are initializing an object. that will not run. try to execute his first piece of code and you will see what I mean. – Dominic May 23 '16 at 15:07

1 Answers1

0

myFunction in your example is an object not a function and submitButton is a property of that object, to access it you'll do this:

window.onload = window.myFunction.submitButton;

update

Something like this will run multiple functions.

 window.onload = function(){
    for(var prop in window.myFunction) { 
      if(window.myFunction.hasOwnProperty(prop) && typeof window.myFunction[prop] === 'function') {
        window.myFunction[prop]();
      }
    }
 };
Neta Meta
  • 4,001
  • 9
  • 42
  • 67