7 April 2011

This tutorial shows how to make image switcher with javascript. You can switch images by using arrows.

HTML:

We have a default image and switcher buttons. Switcher button should switch those images.
Source code viewer
  1. <img src="default_image.png" alt="This image is going to be switched" name="SwitchingImage" />
  2.  
  3. <a href="javascript:NextImage()" style="float:right">Next Image</a>
  4. <a href="javascript:PreviousImage()">Previous Image</a>
Programming Language: HTML

JavaScript - No Looping:

This switcher doesn't loop when it reaches to the end.
Source code viewer
  1. // -1 because array members start from 0.
  2. var NumberOfImages = 5 - 1;
  3.  
  4. var img = new Array(NumberOfImages);
  5.  
  6. img[0] = "image.png";
  7. img[1] = "image2.png";
  8. img[2] = "image3.png";
  9. img[3] = "image4.png";
  10. img[4] = "image5.png";
  11.  
  12. // Array key of current image.
  13. var imgNumber = 0;
  14.  
  15. function NextImage() {
  16. // Stop moving forward when we are out of images.
  17. if (imgNumber < NumberOfImages) {
  18. imgNumber++;
  19. document.images["SwitchingImage"].src = img[imgNumber];
  20. }
  21. }
  22.  
  23. function PreviousImage() {
  24. // Stop moving backward when we are out of images.
  25. if (imgNumber != 0) {
  26. imgNumber--;
  27. document.images["SwitchingImage"].src = img[imgNumber];
  28. }
  29. }
Programming Language: Javascript

JavaScript - Using Images For Buttons:

This doesn't loop either, but uses image buttons. You can easily switch those images, when one end is reached. So you can make the disabled look for the image. The upper part stays the same, so no point to display it twice.
Source code viewer
  1. ...
  2.  
  3. function NextImage() {
  4. if (imgNumber < NumberOfImages) {
  5. if (imgNumber == 0) {
  6. document.images["previous_image_name_attribute"].src = "dir/to/colored_previous_image.png";
  7. }
  8. imgNumber++;
  9. if (imgNumber == NumberOfImages) {
  10. document.images["next_image_name_attribute"].src = "dir/to/grey_next_image.png";
  11. }
  12. document.images["SwitchingImage"].src = img[imgNumber];
  13. }
  14. }
  15.  
  16. function PreviousImage() {
  17. if (imgNumber != 0) {
  18. if (imgNumber == NumberOfImages) {
  19. document.images["next_image_name_attribute"].src = "dir/to/colored_next_image.png";
  20. }
  21. imgNumber--;
  22. if (imgNumber == 0) {
  23. document.images["previous_image_name_attribute"].src = "dir/to/grey_previous_image.png";
  24. }
  25. document.images["SwitchingImage"].src = img[imgNumber];
  26. }
  27. }
Programming Language: Javascript