DIV onload Not Firing JavaScript Method
Solution 1
onload
will not fire for a <div>
element.
You can do that for the document
or body
, or the less desired way of calling the script immediately after the <div>
.
<div id="map_canvas" style="width: 500px; height: 400px;"></div>
<script>
mapAddress();
</script>
Solution 2
onload is only supported by the following HTML Tags:
<body>, <frame>, <frameset>, <iframe>, <img>,
<input type="image">, <link>, <script>, <style>
Solution 3
Don't attach onload
handlers to <div>
elements, just the <body>
element.
A good place to put this is directly on the global object (window
):
window.onload = function () {
// your code
};
Placing an onload
handler on a <div>
doesn't make sense because the element is "loaded" right after it is parsed and added to the DOM tree.
Mike Perrenoud
Mike Perrenoud is a 19-year veteran developer, polyglot, mentor and all around nice guy. He enjoys helping people and making a difference in their lives.
Updated on June 13, 2022Comments
-
Mike Perrenoud almost 2 years
I am using ASP.NET MVC 4 and I have a DIV like this:
<div id="map_canvas" style="width: 500px; height: 400px;" onload="mapAddress();"></div>
Then, in a JavaScript file (that I've verified is loaded) is the
mapAddress
function:function mapAddress() { //In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead var address = $("#Address").val(); geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { var myLatLng = results[0].geometry.location.LatLng; var mapOptions = { center: myLatLng, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: $("#Name").val() + " Location" }); } else { alert("The location of the event could not be mapped because: " + status); } }); }
But for whatever reason it's not being called. Did I misunderstand the
onload
event?Thanks all!
-
Mike Perrenoud over 11 yearsThanks, this worked like a charm. Sorry for my ignorance! Sometimes you wonder, you've been doing this thing for more than a decade and still miss things like this here and there. Just proves we're not perfect.