I trying to create thumbnails which when clicked show up in a main image. I've tested the code and all seems to be in order however the main images are not showing when thumbsnails are clicked. There's a 404 error message showing in chrome. I know the file pathways are correct because when I remove the preventDefault()
the link displays the file containing the image ?
I have played around with this for some time now. Is there an error in the code I'm not seeing or some action I haven't accounted for. I'm new to javascript.
<img id="viewer" src="images/motorbike-girl.jpg" width='450px' />
<div id='thumbs'>
<a href='images/chicks.jpg'><img src='images/chicks-thumb.jpg'/></a>
<a href='images/motorbike-girl.jpg'><img src='images/motorbike-girl-thumb.jpg'/></a>
<a href='images/yamaha.jpg'><img src='images/yamaha-thumb.PNG' /></a>
</div>
var thumbs = document.getElementById('thumbs');
var img = document.getElementById('viewer');
thumbs.onclick = function(event) {
var target = event.target;
while(target != thumbs) {
if(target.nodeName == 'A') {
img.src = this.href;
event.preventDefault();
}
target = target.parentNode;
}
}
This line:
img.src = this.href;
should be:
img.src = target.href;
You should also break
out of the loop once you find the A
node and set the image source.