As I work my way through the textbook for one of my classes, I am practicing by building an image swapping page. The concept is simple - clicking on a thumbnail swaps out the main image and enlarges it as if it were linking to another web page. Despite following the code exactly as it appears in the book, I encounter an error. Here's the code snippet:
var $ = function(id){
return document.getElementById(id);
};
window.onload = function(){
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("main_image");
var imageLinks = listNode.getElementsByTagName("a");
// process image links
var i, image, linkNode, link;
for (i = 0; i < imageLinks.length; i++){
linkNode = imageLinks[i];
// preload image
image = new Image();
image.src = linkNode.getAttribute("href");
// attach event handler
linkNode.onclick = function(evt){
link = this; // "this" refers to the clicked link
// set new image and caption based on the href and title attributes
imageNode.src = link.getAttribute("href");
captionNode.firstChild.nodeValue = link.getAttribute("title");
// prevent default action of the event
if (!evt){
evt = window.event;
}
if (evt.preventDefault){
evt.preventDefault();
}else{
evt.returnFalse = false;
}
};
}
// focus on the first image link
imageLinks[0].focus();
The error arises at
imageNode.src = link.getAttribute("href");
. Upon inspecting my HTML structure:
<body>
<h1>Image Swap With JavaScript</h1>
<p>Click on an image to enlarge.</p>
<ul id="image_list">
<li><a href="images/photo1.jpg" title="Golden Gate">
<img src="thumbnails/thumb1.jpg" alt=""></a></li>
<li><a href="images/photo2.jpg" title="Rocky Coast">
<img src="thumbnails/thumb2.jpg" alt=""></a></li>
<li><a href="images/photo3.jpg" title="Ocean Side">
<img src="thumbnails/thumb3.jpg" alt=""></a></li>
</ul>
<h2 id="caption">Ocean Side</h2>
<p><img id="main-image" src="images/photo3.jpg" alt=""></p>
</body>
I'm left pondering over why this error occurs. Any insights?