biglibigli
biglibigli

Reputation: 59

run more than one javascript function on page load

  1. I want run some javascript functions on page load, which ways are exist and which one is better ?
  2. can i call more than one function in <body onclick="my function();"> ?

Upvotes: 3

Views: 4390

Answers (4)

Jeremy
Jeremy

Reputation: 22415

First, you do not want to force the user to click on the page in order for the functions to execute.

The most basic way to do is:

<body onload="yourFunction();">

Then, in a <script> tag in the <head> have your function call all your other functions:

function yourFunction(){
    function1();
    function2();
    // some other code not in a function...
    //...
}

Upvotes: 5

Alex Netkachov
Alex Netkachov

Reputation: 13522

Executing code on page load is not a trivial task because of cross-browser compatibility. It is better to use one of the frameworks. For example, jQuery:

$(function () { /* your code */ });

As for binding several event functions to element - you can do it with jquery too:

$('#mybytton').click(function () { /* first handler */ });
$('#mybytton').click(function () { /* second handler */ });

or

$('#mybytton').click(function () { /* first handler */ })
    .click(function () { /* second handler */ });

Upvotes: -1

Jad
Jad

Reputation: 932

If you want to add different listeners, you'll need to use javascript. Check the answer to this question (edit: ok "need" is a bit strong, you can still do it directly in the tag :))

Upvotes: 0

George Cummins
George Cummins

Reputation: 28906

<body onload="yourFunction1();yourFunction2();">

Upvotes: 1

Related Questions