I'm a beginner in JavaScript. I wrote this code so the main image get set on whatever thumbnail image the user clicks.
And if the user didn't click on any image the main photo get changed every 10 seconds.
Here's my code (I feel like I'm doing some unnecessary work here in the timers but I can't figure it out):
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Photo Gallery</title>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="mainContainer">
<div id="mainImage">
<img src="img/Flowers_by_Deidameia.jpg" />
</div>
<div id="thumbnails">
<img class="imgThumbnails" src="img/Flowers_by_Deidameia.jpg"/>
<img class="imgThumbnails" src="img/flower.jpg"/>
<img class="imgThumbnails" src="img/cone-flowers-preview.jpg" />
<img class="imgThumbnails" src="img/two_flowers.jpg" />
</div>
</div>
<div id="imgCaption">
</div>
</body>
</html>
JavaScript:
window.onload = function(){
var mainImage = document.getElementById("mainImage").getElementsByTagName("img")[0],
thumbnailImages = document.getElementById("thumbnails").getElementsByTagName("img"),
j = 0;
var startTimer = function(){
stillTimer = setInterval(function(){
j = (j < 3) ? ++j : 0 ;
mainImage.src = thumbnailImages[j].src;
}, 10000);
}
startTimer();
for(i = 0 ; i < thumbnailImages.length ; i++){
thumbnailImages[i].addEventListener("click", function(evt){
clearInterval(stillTimer);
mainImage.src = evt.target.src;
++j;
startTimer();
});
};
}
CSS:
body {
margin: auto;
width: 800px;
height: 800px;
}
#mainContainer {
width: 760px;
height: 800px;
}
#mainImage {
margin: auto;
height: 560px;
}
#mainImage img {
margin: 10px;
width: 740px;
height: 540px;
}
#thumbnails {
padding-top: 10px;
height: 205px;
}
.imgThumbnails {
margin-left: 6px;
height: 186px;
width: 180px;
display: inline;
hover:
}
.imgThumbnails:hover {
cursor: pointer;
}