osagie
osagie

Reputation: 269

Calling onload event with more than function call

I have something like this in my html:

<body onload='myjavascriptfunction1()'

I also want to be able, with the same onload event to call 'myjavascriptfunction2() along with myjavascriptfunction1()'. Please, is this possible?

Upvotes: 0

Views: 53

Answers (3)

palerdot
palerdot

Reputation: 7642

Attach Event Listeners rather than defining onload events in the markup

  document.body.addEventListener("load", do_something(), false);

  function do_something() {
    alert("hello universe");
    //do something here
  }

Refer to Event Listeners documentation for more info. If your event listener has to work on multiple browsers like legacy IE's you might have to define other event listeners like attachEvent. Libraries like jQuery are handy for these needs as you don't have to worry about browser compatibilities.

Upvotes: 0

Preston S
Preston S

Reputation: 2771

Use a generic OnLoad function

<body onload='onLoad()'>

function onLoad(){
    myJSFunction1();
    myJSFunction2();
}

But a better way would be to subscribe to the onload event using addEventListener

window.addEventListener("load", myJSFunction1, false);
window.addEventListener("load", myJSFunction2, false);

JSFiddle

This keeps your JS separate from your HTML and prevents you from adding the ugly onLoad attribute to the body tag.

Upvotes: 0

George Sofianos
George Sofianos

Reputation: 1191

You can do it like this:

<body onload='myjavascriptfunction1();myjavascriptfunction2()'>

or create a function and then call from that function the other functions you want

function myjavascriptfunction1(){
    myjavascriptfunction2();
    myjavascriptfunction3();
}

Upvotes: 1

Related Questions