Reputation: 4442
I am trying to construct a thumbnail slideshow with javascript. I am very new to Javascript so my way of doing it might be a little strange...
The problem I am running into is that I have a main image, and then I have 4 thumbnails. When I click on the first thumbnail it changes the main image, and the first thumbnail. But when I click on the changed thumbnail it needs to change the main image with a different photo (the one that corresponds to the new thumbnail)
I initialize my functions with a call like this:
document.getElementById('thumb1').onclick=thumbs1;
Which uses this function:
function thumbs1(){
num1 = 1;
num2 = 0;
var src1 = largeArray[num1];
var src2 = thumbArray[num2];
document.getElementById('main').src=src1;
document.getElementById('one').src=src2;
document.getElementById('one').id='change';
}
And I am trying to change the id of the new thumbnail to "change" and call another function like this:
document.getElementById('change').onclick=changed;
And this used the following function:
function changed(){
num1 = 0;
var src1 = largeArray[num1];
document.getElementById('change').src=src1;
document.getElementById('change').id='one';
}
When using Firebug I found the error, and I believe it is being caused by the fact that the call to document.getElementById('change').onclick=changed;
. The browser can not find the Element Id "change" because I have not called the function which changed the ID yet.
Does anyone know how to fix this problem. (I know the code is of low quality... I am teaching my self)
Here is a live link to the page: My Page
Thanks for any help!!
Upvotes: 1
Views: 123
Reputation: 5682
var array = //id's of your images here. you could type them static or search your document for images and get their id attribute.
document.addEventListener("click", function(e){
var clicked_image = e.target || e.srcElement; //using jquery can help with this cause older versions of IE are stupid, but depends on if you want to support them.
var id = clicked_image.getAttribute(id);
var temp = document.getElementById("main").src;
for (var i = 0; i < array.length; i++){
if(array[i] == id){
document.getElementById("main").src = clicked_image.src;
clicked_image.src = temp;
}
}
})
That's pretty quick and dirty, you would be better off assigning eventlisteners
to just your images. You would use the same syntax as above, but it should give you an idea of what to do.
With this you don't have to worry about what image got clicked, you just change the main, and you change the thumb to what the main was. So you eliminate the hassle of trying to keep track of what each image is.
Upvotes: 1