How to define number of cycles in animated Image with Javascript - javascript

I have this snipped made by gilly3 (special thanks).
Is there any possibility to define and apply the desired number of cycles? As we can see, the code will repeat the sequences.
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="https://40.media.tumblr.com/fd2e0116f31a0fcdc8f3531dcaaa90dc/tumblr_o0w5avLZFM1rpy0r6o1_540.jpg" />
<img src="https://41.media.tumblr.com/13699ab5ac456da7712fae015ba3a7a5/tumblr_np0yulyrtz1tn6jt3o1_540.jpg" />
<img src="https://41.media.tumblr.com/6f0cea1195cfd37d468dcd51cb8ca5be/tumblr_nz0hywwevQ1s0x1p3o1_r2_540.jpg" />
<img src="https://40.media.tumblr.com/cfa4f49cfcd79b0afa997d9fb746d93e/tumblr_o0kwteTCVD1qzqavpo1_540.jpg" />
<img src="https://40.media.tumblr.com/81b9d21f1b15584cd75be63e3388aa15/tumblr_ni0eqtik0P1qgwfzao1_540.jpg" />
<img src="https://36.media.tumblr.com/605ce3769d8ca286454f1355749aead2/tumblr_ntx88hD8rP1spnyg9o1_500.jpg" />
<img src="https://40.media.tumblr.com/125a40e474d2d4a8eea6e0a28e24df83/tumblr_o11pefcs5m1sh1x48o1_540.jpg" />
<img src="https://41.media.tumblr.com/bb8ab516d0495bfc35e2413611472daa/tumblr_nycp9fWVTc1qcr6iqo1_540.jpg" />
</div>
I have to recognise that I've received a sugestion:
"setInterval returns an interval id. Store that id in a variable and, when you want to stop the animation, pass the id to clearInterval()" but it will be much appreciated a code update (I don't know how to write this in js).

You could do something like this where you clear the interval once it's run a certain number of times:
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
var numberOfCycles = 10; // Set this to whatever you want
var myInterval = setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
if (i === numberOfCycles * frameCount) {
clearInterval(myInterval);
}
}, 100);
}
This requires the least code mutation, but you could also do something similar with setTimeout's.
Snippet here:
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
var numberOfCycles = 3; // Set this to whatever you want
var myInterval = setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
if (i === numberOfCycles * frameCount) {
clearInterval(myInterval);
}
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
<div id="animation">
<img src="https://40.media.tumblr.com/fd2e0116f31a0fcdc8f3531dcaaa90dc/tumblr_o0w5avLZFM1rpy0r6o1_540.jpg" />
<img src="https://41.media.tumblr.com/13699ab5ac456da7712fae015ba3a7a5/tumblr_np0yulyrtz1tn6jt3o1_540.jpg" />
<img src="https://41.media.tumblr.com/6f0cea1195cfd37d468dcd51cb8ca5be/tumblr_nz0hywwevQ1s0x1p3o1_r2_540.jpg" />
<img src="https://40.media.tumblr.com/cfa4f49cfcd79b0afa997d9fb746d93e/tumblr_o0kwteTCVD1qzqavpo1_540.jpg" />
<img src="https://40.media.tumblr.com/81b9d21f1b15584cd75be63e3388aa15/tumblr_ni0eqtik0P1qgwfzao1_540.jpg" />
<img src="https://36.media.tumblr.com/605ce3769d8ca286454f1355749aead2/tumblr_ntx88hD8rP1spnyg9o1_500.jpg" />
<img src="https://40.media.tumblr.com/125a40e474d2d4a8eea6e0a28e24df83/tumblr_o11pefcs5m1sh1x48o1_540.jpg" />
<img src="https://41.media.tumblr.com/bb8ab516d0495bfc35e2413611472daa/tumblr_nycp9fWVTc1qcr6iqo1_540.jpg" />
</div>

Related

how to change a text and image every 5 seconds in javascript and html

hey I wrote a JavaScript code and I managed to make the image change every few seconds but the text is changing alongside with the image but not the correct text is shown here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
<script>
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
setTimeout("changeImage()", 6000);
}
function changeText() {
var txt= document.getElementById("message");
txt.textContent = text[y];
y++;
if(y>= text.length){
y = 0;
}
setTimeout("changeText()", 6000);
}
var text = [], y=0;
text[0] = "MSG1";
text[1] = "MSG2";
text[1] = "MSG3";
setTimeout("changeText()", 6000);
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hello
</h1>
<img id="img"
src="image1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
is there any efficient way to do it my goal is to make 3-5 images on an html webpage that change between each other every few seconds and each image has a different text above it
Combine your two functions into one, so both things happen at the same time:
<script>
function changeImageAndText() {
var img = document.getElementById("img");
img.src = images[x];
var txt = document.getElementById("message");
txt.textContent = text[x];
x++;
if (x >= images.length) {
x = 0;
}
setTimeout("changeImageAndText()", 6000);
}
var text = [],
images = [],
x = 0;
text[0] = "MSG1";
text[1] = "MSG2";
text[2] = "MSG3";
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImageAndText()", 6000);
</script>
Instead of maintaining two arrays have one array of objects each of which contains image and text information. You can then create markup containing both sets of information at once rather than relying on two functions.
This working example uses images from dummyimage.com.
const data = [
{ image: 'https://dummyimage.com/100x100/666/ff0', text: 'Image 1' },
{ image: 'https://dummyimage.com/100x100/222/ff0', text: 'Image 2' },
{ image: 'https://dummyimage.com/100x100/fff/000', text: 'Image 3' },
{ image: 'https://dummyimage.com/100x100/a45/000', text: 'Image 4' },
];
// Cache the element
const div = document.querySelector('div');
// `carousel` is the main function into which we
// pass the data
function carousel(data) {
// `loop` is what `setTimeout` calls every second
// We initialise `count` to 0
function loop(count = 0) {
// Create the HTML using a template string
const html = `
<figure>
<img src="${data[count].image}" />
<figcaption>${data[count].text}</figcaption>
</figure>`;
// Add the markup to the div
div.innerHTML = html;
// Reset the count if we've reached the
// end of the array, otherwise increment it
if (count === data.length - 1) {
count = 0;
} else {
++count;
}
// Call `loop` every second with the
// updated `count` variable
setTimeout(loop, 1000, count);
}
loop();
}
carousel(data);
<div></div>
Additional information
Template/string literals
querySelectorAll
figure
Your code is basically fine as far as timing goes - with intervals as long as 6 seconds you aren't going to notice if one timeout happens a microsecond after the other.
Your problem is a straightforward bug. There is a repetition of text[1] so the MSG2 never gets shown.
This is your snippet with just that change made and it works perfectly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
img {
height: 500px;
width: 450px;
}
h1 {
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button {
margin-left: 45%;
}
</style>
<script>
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if (x >= images.length) {
x = 0;
}
setTimeout("changeImage()", 6000);
}
function changeText() {
var txt = document.getElementById("message");
txt.textContent = text[y];
y++;
if (y >= text.length) {
y = 0;
}
setTimeout("changeText()", 6000);
}
var text = [],
y = 0;
text[0] = "MSG1";
text[1] = "MSG2";
text[2] = "MSG3";
setTimeout("changeText()", 6000);
var images = [],
x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hello
</h1>
<img id="img" src="image1.jpg">
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
However, you mention efficiency, and again at such long time intervals it probably isn't going to make a great deal of difference as the JS is only called every 6 seconds but if you want to make more efficient code then consider ditching JS and using CSS animations instead - the browser will have a chance of using the GPU then.
The way I would do it is this:
const text = ["MSG1", "MSG2", "MSG3"];
const image = ["image1.jpg", "image2.jpg", "image3.jpg"];
const imageObj = document.GetElementById("img");
const textObj = document.GetElementById("message");
let counter = 0;
function ChangeImage() {
if (counter == text.length) {
counter = 0;
}
textObj.innerText = text[counter];
imageObj.src = image[counter];
counter++;
}
setInterval(ChangeImage, 3000); // 3000 = 3 Seconds, 5000 = 5 seconds.
The main thing to remember is to reduce the amount of times you repeat yourself, when looping through an array (when the pointer will be the same always) use the same variable (in this case counter)

Javascript Slideshow Buttons Only Showing 1 Slide

I am working on a slideshow for the homepage of my website. It works, automatically shifting throughout 1-3, but the onclick functions are having some troubles. Every single one of the buttons bring me to my first slide, not the second or the third, just the first. Any help is appreciated, please and thanks!
document.getElementById("left").style.opacity =1;
var currentSlide = 2;
var myVar = setInterval(changeSlide, 5000);
function changeSlide() {
if (currentSlide == 1) {
currentSlide++;
document.getElementById("slide1IMG").src = 'http://theskindealer.com/img/slide1.png';
document.getElementById("left").style.opacity =1;
document.getElementById("right").style.opacity =.5;
} else if (currentSlide == 2) {
currentSlide++;
document.getElementById("slide1IMG").src = 'http://theskindealer.com/img/slide2.png';
document.getElementById("middle").style.opacity =1;
document.getElementById("left").style.opacity =.5;
} else {
--currentSlide;
--currentSlide;
document.getElementById("slide1IMG").src = 'http://theskindealer.com/img/slide3.png';
document.getElementById("right").style.opacity =1;
document.getElementById("middle").style.opacity =.5;
}
}
function firstSlide() {
currentSlide = 1;
myVar = setInterval(changeSlide, 5000);
}
function secondSlide() {
currentSlide = 2;
myVar = setInterval(changeSlide, 5000);
}
function thirdSlide() {
currentSlide = 3;
myVar = setInterval(changeSlide, 5000);
}
<div id="slideshow">
<div id="slide1">
<img src="/img/slide1.png" alt="" style="width:100%;height:100%;position:absolute;" id="slide1IMG">
</div>
<div id="selectors">
<a href="" onclick="firstSlide()">
<div id="left">
</div>
</a>
<a href="" onclick="secondSlide()">
<div id="middle">
</div>
</a>
<a href="" onclick="thirdSlide()">
<div id="right">
</div>
</a>
</div>
</div>
You are using links <a> tags, to handle your clicks, the page is reloading every time you click on one of them, on page reload, it will display the first slide. That is the expected behavior of href="".
The easiest solution is to change your <a> tags for <button> tags, though you could also catch the event and use event.preventDefault() to stop the page from reloading.
<button onclick="firstSlide()">
...
</button>
<button onclick="secondSlide()">
...
</button>
<button onclick="thirdSlide()">
...
</button>
Once you stop navigating away from the page, your code will be setting a new interval every time you handle the click, to avoid that, you could use a setTimeout() at the end of changeSlide(), instead of an interval, or clear the interval on your click handlers
function firstSlide() {
// Change the current slide
currentSlide = 1;
changeSlide();
// Reset the interval
clearInterval(myVar);
myVar = setInterval(changeSlide, 5000);
}
I would probaly rename myVar to something that makes it clear that it is the interval, like refreshSlideInterval.
You could also change the conditionals inside changeSlide to use strict comparisons
if (currentSlide == 1) {...}
to
if (currentSlide === 1) {...}
Since you know that you are working with integers.
Example snippet
const content = document.getElementById("content");
let currentSlide = 2;
let slideCountDown = setTimeout(changeSlide, 3000);
function changeSlide() {
// Clear the timeout
clearTimeout(slideCountDown);
if (currentSlide === 1) {
currentSlide = 2;
content.innerText = 1;
} else if (currentSlide === 2) {
currentSlide = 3;
content.innerText = 2;
} else {
currentSlide = 1;
content.innerText = 3;
}
// Reset the timeout
slideCountDown = setTimeout(changeSlide, 3000);
}
function firstSlide() {
currentSlide = 1;
changeSlide();
}
function secondSlide() {
currentSlide = 2;
changeSlide();
}
function thirdSlide() {
currentSlide = 3;
changeSlide();
}
#container {
display: flex;
flex-direction: column;
align-items: center;
}
#content {
font-size: 5rem;
padding: 2rem;
}
#buttons {
display: flex;
flex-direction: row;
}
<div id="container">
<div id="content">1</div>
<div id="buttons">
<button onclick="firstSlide()">
First
</button>
<button onclick="secondSlide()">
Second
</button>
<button onclick="thirdSlide()">
Third
</button>
</div>
</div>
The setInterval at each select function are not necessary.
According to the changeSlide function, change the currentSlide as follow.
function firstSlide() {
currentSlide = 3;
}
function secondSlide() {
currentSlide = 1;
}
function thirdSlide() {
currentSlide = 2;
}
check this (run the snippet below ) i fixed some syntax errors :
document.getElementById("left").style.opacity =1;
var currentSlide = 1;
var myVar = setInterval(function(){
return changeSlide()
}
,1000);
function changeSlide() {
if (currentSlide == 1) {
currentSlide++;
document.getElementById("slide1IMG").src = 'https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg';
document.getElementById("left").style.opacity =1;
document.getElementById("right").style.opacity =.5;
} else if (currentSlide == 2) {
currentSlide++;
document.getElementById("slide1IMG").src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Stellar_%289460796504%29.jpg/1024px-Stellar_%289460796504%29.jpg';
document.getElementById("middle").style.opacity =1;
document.getElementById("left").style.opacity =.5;
} else if(currentSlide==3){
currentSlide = 1;
document.getElementById("slide1IMG").src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Pillars_of_creation_2014_HST_WFC3-UVIS_full-res_denoised.jpg/1024px-Pillars_of_creation_2014_HST_WFC3-UVIS_full-res_denoised.jpg';
document.getElementById("right").style.opacity =1;
document.getElementById("middle").style.opacity =.5;
}
}
function firstSlide() {
currentSlide = 1;
clearInterval(myVar)
myVar = setInterval(changeSlide(), 1000);
}
function secondSlide() {
currentSlide = 2;
clearInterval(myVar)
myVar = setInterval(changeSlide(), 1000);
}
function thirdSlide() {
currentSlide = 3;
clearInterval(myVar)
myVar = setInterval(changeSlide(), 1000);
}
<div id="slideshow">
<div id="slide1">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Stellar_%289460796504%29.jpg/1024px-Stellar_%289460796504%29.jpg" alt="" style="width:100%;height:100%;position:absolute;" id="slide1IMG">
</div>
<div id="selectors">
<a href="" onclick="firstSlide()">
<div id="left">
</div>
</a>
<a href="" onclick="secondSlide()">
<div id="middle">
</div>
</a>
<a href="" onclick="thirdSlide()">
<div id="right">
</div>
</a>
</div>
</div>

setTimeout not working as intended with css

var myIndex = 0;
var lastIndex = null;
var slides;
window.onload = function ()
{
slides = document.getElementsByClassName("mySlides");
slidePictures();
}
function slidePictures() {
slides[myIndex].style.display = "block";
slides[myIndex].className += " fadeIn";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].className = "mySlides";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].style.display = "none";
console.log("display none");
}, 1000);
}, 2000);
lastIndex = myIndex;
myIndex++;
if (myIndex >= 3)
return;
setTimeout(slidePictures, 4000);
}
.slidesDiv>img {
width: 80%;
height: 80%;
margin-left: 10%;
opacity: 0;
transition: opacity 1s;
}
.fadeIn {
opacity: 1 !important;
transition: opacity 1s;
}
<div class="slidesDiv">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<img class="mySlides" src="//placehold.it/200x80/0bf">
<img class="mySlides" src="//placehold.it/200x80/fb0">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<h1 id="indicator"> Indicator </h1>
</div>
So my issue is that, the image fades in the first time, but then doesn't fade out afterwards, nor does it disappear?
It's definitely problem with the setTimeout functions and I'm wondering what I'm doing/assuming incorrectly.
I edited your code a bit for cleanliness and I also removed the extra transition from .fadeIn as you already had it part of slidesDiv>img.
In your example your program flow is a bit hard to understand, and you are using a lot of variables which are not clear where they come from (like slides and myIndex) so that was part of the reason why it was difficult to figure why it was failing.
Hopefully I understood correctly what you were trying to achieve and the below should work for you. It's definitely not the best in terms of readability and you might be able to extract some of the nested setTimeouts into other functions, but I didn't want to modify too much of your initial code:
var myIndex = 0;
var lastIndex = null;
var slides;
window.onload = function() {
slides = document.querySelectorAll(".mySlides");
slidePictures(slides);
}
function slidePictures(slides) {
var time = 0;
slides.forEach((slide) => {
setTimeout(() => {
slide.style.display = "block";
slide.className += " fadeIn";
setTimeout(function() {
slide.className = "mySlides";
setTimeout(function() {
slide.style.display = "none";
}, 1000);
}, 2000);
}, time);
time += 4000;
});
}
.slidesDiv>img {
width: 80%;
height: 80%;
margin-left: 10%;
opacity: 0;
transition: opacity 1s;
}
.fadeIn {
opacity: 1 !important;
}
Please see this Pen for complete example: http://codepen.io/rarmatei/pen/apramB
var myIndex = 0;
var lastIndex = null;
var slides;
window.onload = function ()
{
slides = document.getElementsByClassName("mySlides");
slidePictures();
}
function slidePictures() {
slides[myIndex].style.display = "block";
slides[myIndex].className += " fadeIn";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].className = "mySlides";
console.log(slides[myIndex]);
setTimeout(function ()
{
slides[myIndex].style.display = "none";
console.log("display none");
// Move indexes here
lastIndex = myIndex;
myIndex++;
}, 1000);
}, 2000);
if (myIndex >= 3)
return;
setTimeout(slidePictures, 4000);
}
.slidesDiv>img {
width: 80%;
height: 80%;
margin-left: 10%;
opacity: 0;
transition: opacity 1s;
}
.fadeIn {
opacity: 1 !important;
transition: opacity 1s;
}
<div class="slidesDiv">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<img class="mySlides" src="//placehold.it/200x80/0bf">
<img class="mySlides" src="//placehold.it/200x80/fb0">
<img class="mySlides" src="//placehold.it/200x80/0fb">
<h1 id="indicator"> Indicator </h1>
</div>
It's pretty hard to tell what you're trying to achieve from your code. I assume that you want the pictures to fade in, and after a certain delay to fade out again?
For that I would highly suggest you to use jQuery. Here's a fiddle I made.
The slidePictures function would now just look like this:
function slidePictures() {
$(".mySlides").each(function(element){
console.log(this);
// 2000 is the duration of the fading in milliseconds
$(this).fadeIn(2000, function(){
// fadeout is delayed 4000 milliseconds
$(this).delay(4000).fadeOut(2000);
});
});
}
If that's not what you need, please provide additional information.
grwag

How to add a fading effect for my JS slideshow?

I have this slideshow JS code that switches images in a div depending on the time we want. However, how can I add a fade in/fade out effect instead of a basic transition with no animation? I am doing this without jQuery, just plain javascript. Here is the link: https://en.khanacademy.org/computer-programming/js-library-exatreojs-slideshow-library/2950604004
here is the code:
var slideShow = function(container, time) {
container = document.getElementById(container);
this.images = [];
this.curImage = 0;
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.display = "none";
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
this.images[i].style.display = "none";
}
this.images[this.curImage].style.display = "block";
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
// old code: window.setTimeout(nextSlide.bind(this), time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);
// old code: slideShow(document.getElementById("slideshow"), 1000);
<div id="slideshow">
<img src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>
You could try this method, if you don't mind that display is always block and I just change opacity of image. So the container has to be relatively positioned and imgs should be absolute
var slideShow = function(container, time) {
container = document.getElementById(container);
this.images = [];
this.curImage = 0;
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.opacity = 0;
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
if (i!=this.curImage) this.images[i].style.opacity = 0;
}
this.images[this.curImage].style.opacity = 1;
this.curImage++;
if (this.curImage>=this.images.length) this.curImage=0;
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
// old code: window.setTimeout(nextSlide.bind(this), time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);
// old code: slideShow(document.getElementById("slideshow"), 1000);
img {
transition: opacity 0.5s;
position:absolute;
top:0;
}
<div id="slideshow">
<img src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>

JS: Slideshow inaccurate result

Hi I write this simple javascript slideshow cause I want to write my own slideshow in javascript. It automatically change the images by a set time interval. But when I try to click the backward and forward function the result is not accurate or the images are in order.
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = 0;
var count = images.length;
function slidingImages()
{
i = i % count;
document.banner.src = images[i];
i++;
}
function forward()
{
i = (i + 1) % count;
document.banner.src=images[i];
}
function backward()
{
if (i <= 0)
{
i = count - 1;
}
else
{
i--;
}
document.banner.src=images[i];
}
window.onload = function()
{
slidingImages(),setInterval(slidingImages, 3000)
};
<center>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<input type="button" value="«prev" onClick="backward()">
<input type="button" value="next»" onClick="forward()">
</center>
What is the solution so my slideshow would be accurate?
This will pause the automatic behavior when the mouse is within the red rectangle and continue in auto mode once the mouse is out of the red rectangle. The buttons of course work as expected.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
fieldset { width: -moz-fit-content; width: -webkit-fit-content; width: fit-content; border: 1px solid red; }
</style>
</head>
<body>
<section>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<fieldset id="control">
<input id="prev" type="button" value="◄">
<input id="next" type="button" value="►">
</fieldset>
</section>
<script>
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = -1;
var count = images.length;
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var control = document.getElementById('control');
var autoSlide;
window.onload = auto;
function auto() {
autoSlide = setInterval(fwd, 3000) };
function pause() {
clearInterval(autoSlide);
}
function fwd() {
if (i >= 0 && i < 2)
{
i += 1;
}
else
{
i = 0;
}
document.banner.src=images[i];
}
function rev() {
if (i > 0 && i <= 2)
{
i -= 1;
}
else
{
i = 2;
}
document.banner.src=images[i];
}
prev.addEventListener('click', function() {
rev();
}, false);
next.addEventListener('click', function() {
fwd();
}, false);
control.addEventListener('mouseover', function() {
pause();
}, false);
control.addEventListener('mouseout', function() {
auto();
}, false);
</script>
</body>
</html>

Categories

Resources