I have the following inline Javascript code:
<a href="javascript:{ document['example'].src = 'cube.png'; document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();'; }">Cube</a>
For your poor tired programmer eyes, here's the expanded version:
document['example'].src = 'cube.png';
document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();';
This code acts as a hyperlink that changes the example
image to an image of a 3D cube and changes a <pre id="constructor">
's content to the appropriate constructor. (This is obviously a tutorial page).
This works perfectly fine in Chrome, but in other browsers, I get either a new page or the whole page's content changed to:
Mesh mesh = new Mesh.Cube();
What is the problem with the code? What puzzles me is that it's valid in a browser and not in another. It's as if the script couldn't find the 'constructor' element and proposed the whole page as a fallback. I'm far from being a Javascript expert, so that's just a wild guess.
I will just answer "What is the problem with the code?"
The href
behaves differently than any onXXX event (hence javascript: protocol). It kind of tries to load new document and put something inside. The worst thing, it catches all output. So, to make it work as-is, you need to catch all statement values as assignments:
var x = document['example'].src = 'cube.png';
var y = document.getElementById('constructor').innerHTML = 'Mesh mesh = new Mesh.Cube();';
all in javascript:{...}
of course.
Also some good comments and explanations here: http://www.west-wind.com/weblog/posts/9899.aspx