+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...]
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.