Welcome to WebmasterWorld Guest from 54.198.143.210

Forum Moderators: open

Message Too Old, No Replies

switching around images in JavaScript

     
11:42 pm on Mar 4, 2012 (gmt 0)

New User

5+ Year Member

joined:Mar 4, 2012
posts: 1
votes: 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.
3:14 pm on Mar 5, 2012 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts:5007
votes: 21


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.
8:09 pm on Mar 5, 2012 (gmt 0)

Junior Member

5+ Year Member

joined:Feb 7, 2010
posts: 119
votes: 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';
}
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members