PDA

View Full Version : calling a function on body onload



gurmeet
01-15-2011, 08:39 AM
how i can cal a function on body onload?

i dont want to use <body onload="func()">

what i the alternative for this coding?

the script is also defined within the page.....

but need to call that functions on body loading.....

jscheuer1
01-15-2011, 11:50 AM
Are you using jQuery? If so:


<script type="text/javascript">
jQuery(window).load(func);
</script>

Or if document ready which happens sooner is OK:


<script type="text/javascript">
jQuery(function($){
func();
});
</script>

Regular javascript:


<script type="text/javascript">
if (window.addEventListener){
window.addEventListener('load', func, false);
}
else if (window.attachEvent){
window.attachEvent('onload', func);
}
</script>

There's also:


<script type="text/javascript">
window.onload = func;
</script>

But that has almost as many problems as the <body onload="func();"> method does.

Or if you want to use document ready, place this before the closing </body> tag:


<script type="text/javascript">
func();
</script>

Aside from the last one (document ready, regular javascript), these may all go in the head or wherever pretty much and their code may go in an external file that's called, as long as they come after func() is defined.

There are variations on at least some of these methods, probably even other methods. But these should give you enough options to work with for now. If you have something in particular in mind and none of these seems ideal, let me know what the circumstances are.

gurmeet
01-17-2011, 06:39 AM
thanx a lot dear .......................