I'm trying to append a function to the body tag's onload event...

<body onload="Do_This();"...>
...
...
<script....>
document.body.onload =+ " And_This();";
alert(document.body.onload);
</script>

The alert reports "undefinedDo_This();". The Do_This() function does load (and run) but I want both funcions to run on the onload event. The body tag is in a php "header" file that is included in the file the holds the script.

Thanks

Dani AI

Generated

The line document.body.onload =+ " And_This();"; is the root cause. =+ is not an append operator (and += would only append to a string). The DOM onload handler is normally a function reference, not a string, so mixing inline onload="Do_This();" with string concatenation produces unpredictable results (the "undefinedDo_This();" symptom). Treat handlers as functions rather than text.

Several valid approaches already shown in the replies: ’s idea of calling both functions from a single handler, ’s preservation of an existing handler, and ’s combined assignment all work. A more robust, cross‑browser pattern is to register functions with the load event instead of trying to concatenate handler text. The helper below preserves any existing handler, uses modern listeners where available, and falls back safely for old IE:

function addLoadEvent(fn) {
  if (window.addEventListener) {
    window.addEventListener('load', fn, false);
  } else if (window.attachEvent) {
    window.attachEvent('onload', fn);
  } else {
    var prev = window.onload;
    if (typeof prev === 'function') {
      window.onload = function() { prev(); fn(); };
    } else {
      window.onload = fn;
    }
  }
}

/* usage */
addLoadEvent(Do_This);
addLoadEvent(And_This);

Notes and cautions: do not assign handler code as strings; pass function references. The && trick mentioned by can short‑circuit if one function returns false. If a script runs before the document body exists, referencing document.body may be null—attach to window load or place the script after the markup. The helper above avoids overwriting other handlers and is suitable when the header is shared or cannot be edited (the situation described by and tested historically by ).

Recommended Answers

All 4 Replies

You can either define a third function, which would have the sole purpose of calling the other two functions.

Or, you can comma separate the two functions in your onload attribute.

Or, you can concantenate them with the "&&" operator:

<body onload="return (Do_This() && Do_That())" >

(which is a useful construct if the functions return booleans).

Lastly, you can just include the "And_This()" function in a separate script body at the very end of your document. It will run "inline" when the browser encounters it.

This page demonstrates a technique that can be used to add functions to a body onload, or similar attribute. The beauty of this is that it can be used in situations where your project does not control ownership of the header section of the page, but you want to assign onload or similar behaviours to a page, without destroying the behaviour that already exists.

<html> 

	<head>

		<script type="text/javascript">
		function Do_This(){ alert("hello world"); }
		</script>
		
		
		<title>test</title>
	</head>	
	<body onload="Do_This();" onunload="Do_This();">
	
		<h1>hello world</h1>
		...
		...
		<script type="text/javascript">
			var oldFunction = null;
			function And_This(){ 
				if(oldFunction){ oldFunction(); }
				alert("tuna fish"); 
			}
			function closingFunction(){ 
				if(oldUnloadFunction){ oldUnloadFunction(); }
				alert("closing"); 
			}
			function loadBody(){
				oldFunction = window.onload;
				
				window.onload = And_This;
				alert(window.onload);
			}
			
			var oldUnloadFunction = null;
			function unloadBody(){
				oldUnloadFunction = window.onunload;
				
				window.onunload = closingFunction;
				alert(window.onunload);
			}
			
			loadBody();
			unloadBody();
		</script>
	</body>
</html>

What happens here is the loadBody and unloadBody functions are called inline when the page is being drawn. At this stage the body.onload attribute has been set (you access this using the window.onload attribute). If you print this attribute, you will notice that it is a function, with the initially defined onload function forming the body of the function. This way the javascript engine preserves the arguments that have been provided.

The loadBody function then stores the current function in a global pointer variable. That can then be called as a function in the newly defined onload function.

This has been tested in Internet Explorer 6.0.2800.1106 and Mozilla Firefox 1.0.3 with build string: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3

Hy NimbusSoftware, well here is a code for make two functions or more in the body tag.

/*
onloadfunctions.js
*/
function Do_This() {     
   alert(7);  
}  
function And_This() {
   alert(8);
}
window.onload=function(){
   Do_This();
   And_This();
}

This can be a good form for solve the problem.

Member Avatar for Member #334542
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<script language="javaScript">
function Do_This() {     
   alert(7);  
   And_This();
}  
function And_This() {
   alert(8);
}
</script>
</head>

<body onLoad="Do_This();">
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.