I’m trying to make asides in an HTML document. The asides are supposed to be like inline footnotes. When the reader mouses over a bullet, the full text of the aside is displayed. When the reader mouses out, the text is hidden again. I’m trying to minimize the amount of HTML needed to make this work, so I’m using <span class="aside"... instead of <span onmousover="showAside();"...
Anyway, I’m fairly new to JavaScript, and I’m running into what must be a really novice error that I can’t seem to figure out. When I load the test-case below in a browser, the text of the aside is replaced by a bullet as intended. But when I mouse over or out of the bullet I get the error "this.element is undefined". But it is defined, in the class prototype! What gives?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/ecmascript">
<!--
var asides = [];
// object prototype
function Aside(aside_element)
{
this.element = aside_element;
this.text = this.element.innerHTML;
this.element.onmouseover = this.show;
this.element.onmouseout = this.hide;
this.hide();
}
Aside.prototype.hide = function()
{
this.element.innerHTML = "•";
}
Aside.prototype.show = function()
{
this.element.innerHTML = this.text;
}
// get all <span> elements of class "aside"
function make_asides()
{
span_elements = document.getElementsByTagName("span");
for ( var i = 0, len = span_elements.length; i < len, span_element = span_elements[i]; ++i )
{
if ( span_element.className == "aside" )
asides.push(new Aside(span_element));
}
return asides;
}
// initialize script
window.onload = function()
{
make_asides();
}
-->
</script>
<title>Test Case</title>
</head>
<body>
<p>Hover over the bullet and see the magic text! <span class="aside">This is the magic text.</span></p>
</body>
</html>
Because the scoping is wrong, you need to work with closures