Reputation: 803
Well, I've been at this all day. I'm a noob so its frustrating. I wondering how do you add a previous and next link to the slider below. I am wanting to do everything in pure javascript no jquery libraries. Anyway here is the code. I feel I tried everything. This is so much easier in JQuery, but I need to learn pure javascript better.
<div id="container" onmouseover="stopFunc();" onmouseout="resumeFunc();">
<img src="#" width="250px" height="145px" id="Box" style="margin: 15px;">
<div id="imageDesc" style="margin: 15px;"></div>
<a href="JavaScript:previousImage()" id="prevlink">Previous</a>
<a href="JavaScript:nextImage()" id="nextlink">Next</a>
</div><!-- End container -->
<script type="text/javascript">
var imageDescription = document.getElementById("imageDesc");
var featureImg = document.getElementById("Box");
var index = 0;
var imageArray = [
{src:"images/image1.jpg", des:"description1"},
{src:"images/image2.jpg", des:"description2"},
{src:"images/image3.jpg", des:"description3"},
{src:"images/image4.jpg", des:"description4"}
];
function newImage() {
document.getElementById("container").style.visibility="visible";
featureImg.setAttribute("src", imageArray[index].src);
imageDescription.innerHTML = imageArray[index].des;
index++;
if (index >= imageArray.length) {
index = 0;
}
}
var myTimerControl = setInterval(function(){newImage()},3000);
function stopFunc() {
clearInterval(myTimerControl);
}
function resumeFunc() {
myTimerControl = setInterval(function() {newImage()}, 3000);
}
</script>
Upvotes: 1
Views: 137
Reputation: 3444
This is a little silly since it initializes with -1 but it works... Also note that there is no nextImage() function now, you simply reuse newImage()
<a href="JavaScript:newImage()" id="nextlink">Next</a>
...
var imageDescription = document.getElementById("imageDesc");
var featureImg = document.getElementById("Box");
var index = -1;
var imageArray = [
{src:"images/image1.jpg", des:"description1"},
{src:"images/image2.jpg", des:"description2"},
{src:"images/image3.jpg", des:"description3"},
{src:"images/image4.jpg", des:"description4"}
];
newImage();
function newImage() {
index++;
if (index >= imageArray.length) {
index = 0;
}
document.getElementById("container").style.visibility="visible";
featureImg.setAttribute("src", imageArray[index].src);
imageDescription.innerHTML = imageArray[index].des;
}
function previousImage() {
index--;
if (index < 0) {
index = imageArray.length-1;
}
featureImg.setAttribute("src", imageArray[index].src);
imageDescription.innerHTML = imageArray[index].des;
}
It calls new image immediately which means you won't have to wait for the first timer run in order to see an image. You could also refactor a bit to make it much simpler but the main concept is --Incrementing/decrementing index before you display makes it clearer otherwise your current index value doesn't represent what's actually being shown.
Upvotes: 1