- I want run some javascript functions on page load, which ways are exist and which one is better ?
- can i call more than one function in
<body onclick="my function();">
?
Asked
Active
Viewed 4,354 times
3

biglibigli
- 59
- 3
- 8
4 Answers
5
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...
//...
}
0
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 :))
-1
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 */ });

Alex Netkachov
- 13,172
- 6
- 53
- 85
-
2he mentions nothing of jQuery in his post – Jimmy May 18 '11 at 14:06
-
"I want run some javascript functions on page load, which ways are exist and which one is better" - using jQuery is one of the ways and I think that it is the best one. What's problem? – Alex Netkachov May 18 '11 at 18:05
-
1I didn't downvote you, but it gets old when people ask JS questions and every answer is "use jquery!" even when it isn't needed, he simply wanted to call multiple functions on the body onload event, jQuery isn't the best way to do that at all. Load a library from an external resource just for a couple functions? – Jimmy May 18 '11 at 18:12