Bunny Rabbit
Bunny Rabbit

Reputation: 8411

disappearing google map

> <script type="text/javascript"
    src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    marker = new google.maps.Marker({
    position : latlng,
    title : "hello world",
    draggable : true
    });
   marker.setMap(map)
  }
  function write(){
    //var positon = marker.getPosition()
    alert('position')
  }
</script>
</head>
<body onload="initialize()">
  <div id="map_canvas"></div>
  <input type='button' value ='position' onClick="write()">
</body>
</html>

whenever i click on the button called position the map disappears why is that so ?

Upvotes: 2

Views: 3205

Answers (2)

bobince
bobince

Reputation: 536409

+1 Jens's answer is correct. However saying write should not normally give you document.write. window properties act as globals, but document properties do not:

function write(){
    alert('position')
}

mybutton.onclick= function() {
    write(); // this is fine!
};

The trick is that when you write an inline event handler attribute, the properties of that element and its ancestor elements get dumped into your scope. I'm not sure this is actually documented anywhere, and certainly the exact behaviour will vary between browsers, but it's an old, well-established, and highly dangerous feature:

<input onclick="alert(value);" value="A"/>  // alerts A

<form method="get"><input onclick="alert(method)"/></form> // alerts get

Because document is the top ancestor of all DOM nodes in the page,

<div onclick="alert(write)"/> // alerts the `document.write` function

This means that you can't refer to any global variable or function in an inline event handler attribute that happens to have the same name as a member of an ancestor Node. And since new versions of browsers are released all the time, introducing new DOM properties, any use of any global variable or function in an event handler attribute is likely to break in the future.

This is another reason we never use inline event handler attributes.

[All these examples assume that alert resolves to window.alert, ie that no-one has happened to put an alert property on any of the ancestor DOM nodes...]

Upvotes: 15

Jens Roland
Jens Roland

Reputation: 27770

write() is a reserved Javascript function -- when you call it, you are executing document.write() which (since you are calling it after the document has already finished writing) will rewrite the whole page.

Try renaming it myWrite() instead.

Upvotes: 2

Related Questions