| switching around images in JavaScript
|
RSLee

msg:4424842 | 11:42 pm on Mar 4, 2012 (gmt 0) | I'm trying to create a javascript code that'll let me replace a thumbnail image by clicking one of three smaller identical images beside it. Unfortunately, I can not get the code to function as I wish. I am not allowed to alter the existing HTML code, so I am pretty much forced to do this with pure javascript. This is what I've inititially put together.
window.onload=setupPhotos;
function setupPhotos(){ var smallpics0 = "images/small/black_bear.jpg"; var smallpics1 = "images/small/black_bear1.jpg"; var smallpics2 = "images/small/black_bear2.jpg"; smallpics0.onclick=photo0; smallpics1.onclick=photo1; smallpics2.onclick=photo2; }
function photo0(){ var img = new Image(); img.src=document.getElementById("bear-thumb").src="images/thumbnails/black_bear.jpg"; }
function photo1(){ document.getElementById("bear-thumb").src="images/thumbnails/black_bear1.jpg"; }
function photo2(){ document.getElementById("bear-thumb").src="images/thumbnails/black_bear2.jpg"; } Can somebody please help me find out what I'm doing wrong here? I really need some help here.
|
Fotiman

msg:4425080 | 3:14 pm on Mar 5, 2012 (gmt 0) | Welcome to WebmasterWorld! var smallpics0 = "images/small/black_bear.jpg";
|
| smallpics0 is the string "images/small/black_bear.jpg" smallpics0.onclick=photo0;
|
| The onclick handler of the string "images/small/black_bear.jpg" is photo0? You need to attach the handler to an element, not to a string.
|
nyteshade

msg:4425218 | 8:09 pm on Mar 5, 2012 (gmt 0) | I'm making some assumptions here so forgive me if it's not entirely the answer you need and it just formed out of my head and it's my first time trying to help here with code:
var d=document, imgs = d.getElementsByTagName('img');
for(var i=0; i<imgs.length; i++){ imgs[i].id='smallpics'+i; }
d.getElementById(smallpics0).onclick=function(){ d.getElementById(bear-thumb).src = 'images/small/black_bear0.jpg'; } d.getElementById(smallpics1).onclick=function(){ d.getElementById(bear-thumb).src = 'images/small/black_bear1.jpg'; } d.getElementById(smallpics2).onclick=function(){ d.getElementById(bear-thumb).src = 'images/small/black_bear2.jpg'; }
|
|
|