Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add event handler for body.onload by Javascript within <body> part

We want to include a maps from Google Maps API in our document. The documentation tells to initialize the map with a function called by the onload() event of the body.

The ordinary way to call:

<body onload="initialize_map();"> 

This doesn't work out for us because we're using Template::Toolkit and the <body> tag is already included in our wrapper. In short: The <body> tag is already printed when our Javascript code starts running.

I tried something like this but it does only work for onclick, not onload. I guess that's because the Javascript code is beneath the <body> tag itself.

var body = document.getElementsByTagName("body")[0];  body.addEventListener("load", init(), false);  function init() {         alert("it works!"); }; 

Any help how to fire up a Google Maps map appreciated!

like image 535
Daniel Böhmer Avatar asked Feb 22 '11 18:02

Daniel Böhmer


People also ask

Is onload an event handler attribute?

To handle the load event on images, you use the addEventListener() method of the image elements. You can assign an onload event handler directly using the onload attribute of the <img> element, like this: <img id="logo" src="logo. png" onload="console.


2 Answers

body.addEventListener("load", init(), false); 

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false); 

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.

like image 98
epascarello Avatar answered Sep 19 '22 14:09

epascarello


You should really use the following instead (works in all newer browsers):

window.addEventListener('DOMContentLoaded', init, false); 
like image 40
Jacob Lauritzen Avatar answered Sep 20 '22 14:09

Jacob Lauritzen