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>
Related
I would like to build an image gallery like this where pictures keep looping automatically but at the same time, it's possible to interact through the gallery using the mouse wheel as well. I would also achieve an effect like that where images, instead of scrolling out of the screen shrink on the side.
So I was trying to understand where to start and I couldn't find any library for the task so I tried from scratch using vanilla js, this is my attempt.
var testArray = document.querySelectorAll(".image");
var totImg = testArray.length;
var contIterazioni = 0;
var test = testArray[contIterazioni];
var bounding = test.getBoundingClientRect();
function LoopFunction() {
setInterval(galleryScroll, 20);
}
function galleryScroll() {
test = testArray[contIterazioni];
bounding = test.getBoundingClientRect();
if (bounding.left == 0) {
//console.log("immagine bordo sx");
if (test.width > 0) {
test.width = test.width - .25;
} else {
contIterazioni = contIterazioni + 1;
if (contIterazioni >= totImg){
contIterazioni = 0;
}
}
}
}
LoopFunction();
body{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<div class="container">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
<img src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="" class="image">
<img src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="" class="image">
</div>
Unfortunately, I couldn't figure out how to loop the images. Can you help me understand how to do it? Do you think my approach can be a good one? or would you recommend other ways to get that effect?
Thanks!
Use for loop when you go through all images to set their width to their initial value. Also add extra three images from start of the carousel so there wouldn't be empty space when it comes to an end.
var testArray = document.querySelectorAll(".image");
var totImg = testArray.length;
var contIterazioni = 0;
var test = testArray[contIterazioni];
var bounding = test.getBoundingClientRect();
var imgsWidths = []
window.onload = () => {
for(i = 0; i < testArray.length; i++) {
imgsWidths[i] = testArray[i].width
}
}
function galleryScroll() {
test = testArray[contIterazioni];
bounding = test.getBoundingClientRect();
if (bounding.left == 0) {
if (test.width > 0) {
test.width = test.width - 2;
} else {
contIterazioni = contIterazioni + 1;
if (contIterazioni >= totImg - 3){
for(i = 0; i < testArray.length; i++) {
testArray[i].width = imgsWidths[i]
}
contIterazioni = 0;
}
}
}
window.requestAnimationFrame(galleryScroll)
}
window.requestAnimationFrame(galleryScroll);
body{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<div class="container">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
<img src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="" class="image">
<img src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="" class="image">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
</div>
While keeping your same approach, this should work similarly as the example you provided. If you want the slideshow to keep it's width, all images should have the same width. Your error was not adding back the image that dissapeared to the container, at the end and with it's original width, or as in this case expanding again.
// From https://www.javascripttutorial.net/javascript-queue/
function Queue() {
this.elements = [];
}
Queue.prototype.enqueue = function(e) {
this.elements.push(e);
};
Queue.prototype.dequeue = function() {
return this.elements.shift();
};
Queue.prototype.isEmpty = function() {
return this.elements.length == 0;
};
Queue.prototype.peek = function() {
return !this.isEmpty() ? this.elements[0] : undefined;
};
Queue.prototype.length = function() {
return this.elements.length;
}
let images = new Queue();
document.querySelectorAll(".image").forEach(img => images.enqueue(img));
var totImg = images.length();
var first = images.dequeue();
var last;
var firstWidth = first.width;
var lastWidth = 0.0;
var bounding = first.getBoundingClientRect();
var originalWidth = first.width;
var lastOriginalWidth = 0.0;
var step = 1.0;
var lastStep = 0.0;
function LoopFunction() {
setInterval(galleryScroll, 20);
}
function galleryScroll() {
bounding = first.getBoundingClientRect();
if (bounding.left == 0) {
//console.log("immagine bordo sx");
if (first.width > 0) {
firstWidth -= step;
if (firstWidth < 0) {
firstWidth = 0;
}
first.style.width = firstWidth + 'px';
} else {
if (last && last.width != lastOriginalWidth) {
last.width = lastOriginalWidth;
}
let container = document.querySelector('.container');
container.removeChild(first);
last = first;
lastOriginalWidth = originalWidth;
last.width = 0.0;
lastWidth = 0.0;
images.enqueue(last);
container.appendChild(last);
first = images.dequeue();
originalWidth = first.width;
firstWidth = originalWidth;
lastStep = step * lastOriginalWidth / originalWidth;
}
}
if (last && last.width <= lastOriginalWidth) {
lastWidth += lastStep;
last.style.width = lastWidth + 'px';
if (last.width > lastOriginalWidth) {
last.width = lastOriginalWidth;
}
}
}
LoopFunction();
body {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<div class="container">
<img src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="" class="image">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="" class="image">
<img src="https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg" alt="" class="image">
<img src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="" class="image">
<img src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="" class="image">
</div>
Update #1
As requested by OP, here is some further explenation of the changes I made:
I used a simple queue from javascripttutorial to have a data structure that reflects the objective, i.e. having images that move from right to left, and once they "exit" the scene, can get enqueued again.
Following this concept, we need pointers to both head and tail of the queue in order to update their animation, in particular first, firstWidth and originalWidth are used respectively to point to the head, keep track of its current width during the animation and the originalWidth to which it should return when re-entering the scene. Similarly, this happens for the last as well.
Once this is in place, our loop will be made of two parts, one that handles the head animation and moves the images in the queue when the head image reaches width == 0 and one that handles the tail re-entering the scene and expanding. To achieve continuity, we use a simple proportion after we have our new queue: step : originalWidth = lastStep : lastOriginalWidth, which we use to determine at each frame how much respectively the head and tail images compress and expand. as step is a fixed parameter, lastStep is easily computed through simple arithmetics: lastStep = step * lastOriginalWidth / originalWidth.
The code:
let container = document.querySelector('.container');
container.removeChild(first);
last = first;
lastOriginalWidth = originalWidth;
last.width = 0.0;
lastWidth = 0.0;
images.enqueue(last);
container.appendChild(last);
first = images.dequeue();
originalWidth = first.width;
is just a contextual switch over the changing the queue, where the pointers and respective data get update to reflect the changes in the data structure. So the first becomes last, the next image in the queue is the new compressing first, as such originalWidth shifts.
Let's go further
Now, to achieve your desired implementation, this still needs some work. First of all, the queue should only reflect the actual carousel, not all the images you have, so ideally you would have a first static data structure with all the images and respective metadata, in this case we mainly need their original width. then you would have a queue representing the images that are being animated.
Now, you can either reuse this code and change the width of the images to be all equal and fit the viewport you are using for your animation, which should work fine. The other option is to mirror the code for the head image to the tail, have a fixed step, so while the head compresses of step pixels, the tail expands of the same step pixels, and when the tail reaches maximum width, introduce a new image at the end of the queue which becomes the new tail.
To go in further detail on the last, the algorithm would look something like this:
initialize static list of image containers with their respective width (imgList);
initialize an empty queue (imgQueue);
initialize a pointer pointing to the last image introduced in the queue (listPtr);
get the width of the viewport your carousel should fill (vpWidth);
while you have not filled such width, keep adding images to the queue and moving the listPtr left in the imgList;
have looping function similar to the one above but where the if over last replicates similar steps to the first ones;
This should be everything, I will work on the code in a while, now I need some sleep ;).
Update #2
Okay! Worked out something that actually works decently. If you have suggestions please let me know, in the meanwhile, here it is:
// From https://www.javascripttutorial.net/javascript-queue/
function Queue() {
this.elements = [];
}
Queue.prototype.enqueue = function(e) {
this.elements.push(e);
};
Queue.prototype.dequeue = function() {
return this.elements.shift();
};
Queue.prototype.isEmpty = function() {
return this.elements.length == 0;
};
Queue.prototype.first = function() {
return !this.isEmpty() ? this.elements[0] : undefined;
};
Queue.prototype.length = function() {
return this.elements.length;
};
// Added function to peek last element in queue
Queue.prototype.last = function() {
return !this.isEmpty() ? this.elements[this.elements.length - 1] : undefined;
};
// Added function that pops the head, enqueues it and returns it
Queue.prototype.shift = function() {
const head = this.dequeue();
this.enqueue(head);
return head;
}
// Returns a queue of HTMLElements based on the given class
function loadQueue(className) {
const rQueue = new Queue();
document.querySelectorAll('.' + className).forEach(image => rQueue.enqueue(image));
return rQueue;
}
// Queue of images to be added to the animation queue
const imgQueue = loadQueue('image');
// Images being animated inside the div
const imgAnimQueue = new Queue();
// To limit calls to the carousel
const carousel = $('.container');
function init() {
// Width of the viewport being used for the animation
// TODO: this shoud update whenever the page is resized, or at least the div
const vpWidth = carousel.width();
// Keeps track of the width of the images added to the animation queue
var currentFilledWidth = 0;
// Now that we have loaded the static information, let's clear the div
// that will be used as carousel, so that we can add the correct number
// of images back in
carousel.empty();
// Filling the animation queue
while (currentFilledWidth < vpWidth) {
// In order not to change the static data, we clone the image HTMLElement
const img = $(imgQueue.shift()).clone();
// Enqueuing the new image in the animation queue
imgAnimQueue.enqueue(img);
// Adding this image into the carousel
img.appendTo(carousel);
currentFilledWidth = currentFilledWidth + img.width();
// If we overflow the carousel width, we set the tail image to fill
if (currentFilledWidth > vpWidth) {
const overflow = currentFilledWidth - vpWidth;
img.width(img.width() - overflow);
currentFilledWidth -= overflow;
}
}
const step = 1;
var firstWidth = imgAnimQueue.first().width();
var lastWidth = imgAnimQueue.last().width();
// Now the loop can start
window.requestAnimationFrame(animateCarousel);
// Main function that animates the carousel
function animateCarousel() {
let first = imgAnimQueue.first();
let last = imgAnimQueue.last();
// If the image is still not disappeared, keep compressing it
if (firstWidth > 0) {
firstWidth -= step;
if (firstWidth < 0) firstWidth = 0;
first.width(firstWidth);
// Otherwise, remove it from the carousel and update all the data structs
} else {
first.remove();
imgAnimQueue.dequeue();
if (imgAnimQueue.first() != last) {
first = imgAnimQueue.first();
firstWidth = first.width();
} else {
first = last;
firstWidth = lastWidth;
imgAnimQueue.enqueue($(imgQueue.shift()).clone());
last = imgAnimQueue.last();
lastWidth = last.width();
last.appendTo(carousel);
}
}
if (lastWidth <= last.attr("data-original-width")) {
lastWidth += step;
// The image has completely expanded, let's introduce the next one
if (lastWidth >= last.attr("data-original-width")) {
last.width(last.attr("data-original-width"));
imgAnimQueue.enqueue($(imgQueue.shift()).clone());
last = imgAnimQueue.last();
last.width(0);
lastWidth = last.width();
last.appendTo(carousel);
// Otherwise just keep expanding it
} else {
last.width(lastWidth);
}
}
window.requestAnimationFrame(animateCarousel);
}
}
body {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
display: flex;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var loadedImages = 0;
const count = 4;
function loadImage(img) {
if (loadedImages != count) {
$(img).attr("data-original-width", $(img).width());
loadedImages += 1;
if (loadedImages == count) init();
}
}
</script>
<div class="container">
<img onload="loadImage(this)" src="https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg" alt="1" class="image">
<img onload="loadImage(this)" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg" alt="2" class="image">
<img onload="loadImage(this)" src="https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg" alt="3" class="image">
<img onload="loadImage(this)" src="https://www.orlandocatcafe.com/wp-content/uploads/2020/07/14.png" alt="4" class="image">
</div>
I have three images which my two div's switch between. However, the animation appears too rough. How do I apply a fade right before the switch?
<div class="my-images">
<div id="image-1"></div>
<div id="image-2"></div>
</div>
<script>
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("image-1").style.backgroundImage = images[x];
document.getElementById("image-2").style.backgroundImage = images[x];
}
function startTimer() {
setInterval(displayNextImage, 10000);
}
var images = [],
x = 0;
images[0] = "url('images/snow.jpeg')";
images[1] = "url('images/nike.jpeg')";
images[2] = "url('images/motor.jpeg')";
</script>
This loops continuously so I do not want it just fading in on the first load.
Without JQuery you'll have cross-browser compatibility issue.
So i suggest you to use JQuery to achieve this.
<div class="my-images">
<div class="my-image" id="image-1"></div>
<div class="my-image" id="image-2"></div>
</div>
<script>
function displayNextImage() {
$("#image-" + x).css('backgroundImage', images[x]).show('slow');
x++;
}
var images = [],
x = 0;
images[0] = "url('images/snow.jpeg')";
images[1] = "url('images/nike.jpeg')";
images[2] = "url('images/motor.jpeg')";
</script>
And you have to add this to css:
.my-image{
display:none;
}
In case you not use display: block to you element:
Your CSS will be:
.my-image{
display:whatYouWant;
}
Then need add the document ready() function and change show() to fadeIn():
$(document).ready(function(){
$(".my-image").hide();
});
function displayNextImage() {
$("#image-" + x).css('backgroundImage', images[x]).fadeIn('slow');
x++;
}
This will work because fadeIn() set to display the previous value.
If you want div visible before image adding, remove $(document).ready() call and edit displayNextImage():
function displayNextImage() {
$("#image-" + x).hide().css('backgroundImage', images[x]).fadeIn('slow');
x++;
}
You can do it with CSS animation, for each cycle:
1) swap the image sources like you are already doing
2) reset the fade in animation, more info here
3) increment your index
const imgs = [
'https://source.unsplash.com/iMdsjoiftZo/100x100',
'https://source.unsplash.com/ifhgv-c6QiY/100x100',
'https://source.unsplash.com/w5e288LU8SU/100x100'
];
let index = 0;
const oldImage1 = document.getElementById('oldImage1');
const newImage1 = document.getElementById('newImage1');
const oldImage2 = document.getElementById('oldImage2');
const newImage2 = document.getElementById('newImage2');
window.setInterval(() => {
// put new image in old image
oldImage1.src = newImage1.src;
oldImage2.src = newImage2.src;
// Set new image
newImage1.src = imgs[index];
newImage2.src = imgs[index];
// reset animation
newImage1.style.animation = 'none';
newImage1.offsetHeight; /* trigger reflow */
newImage1.style.animation = null;
newImage2.style.animation = 'none';
newImage2.offsetHeight; /* trigger reflow */
newImage2.style.animation = null;
// increment x
index = index + 1 >= imgs.length ? 0 : index + 1;
}, 1500);
.parent {
position: relative;
top: 0;
left: 0;
float: left;
}
.oldImage1 {
position: relative;
top: 0;
left: 0;
}
.newImage1 {
position: absolute;
top: 0;
left: 0;
}
.oldImage2 {
position: relative;
top: 0;
left: 100;
}
.newImage2 {
position: absolute;
top: 0;
left: 100;
}
.fade-in {
animation: fadein 1s;
}
#keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
<div class="parent">
<img id="oldImage1" class="oldImage1" src="https://source.unsplash.com/ifhgv-c6QiY/100x100" />
<img id="newImage1" class="newImage1 fade-in" src="https://source.unsplash.com/w5e288LU8SU/100x100" />
</div>
<div class="parent">
<img id="oldImage2" class="oldImage2" src="https://source.unsplash.com/ifhgv-c6QiY/100x100" />
<img id="newImage2" class="newImage2 fade-in" src="https://source.unsplash.com/w5e288LU8SU/100x100" />
</div>
I am learning javascript. I have made a image slider but want to add text to each slide I have 5 images just want to add the text to each slide and it be in the middle and centre from top to bottom. Thanks guys
var i = 0;
var images = [];
var time = 3250;
// Image List
images[0] = 'http://lorempixel.com/300/200';
images[1] = 'http://placehold.it/300x200';
images[2] = 'http://lorempixel.com/300/200';
images[3] = 'http://placehold.it/300x200';
images[4] = 'http://lorempixel.com/300/200';
// Change Image
function changeImg(){
document.slide.src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
* {margin:0;padding:0;box-sizing:border-box}
#wrapper {
width: 800px;
height: 400px;
margin: 50px auto;
}
<h1>JS Slider </h1>
<div id="wrapper">
<img name="slide" alt="slide image">
</div>
In order to display unique text per picture, you first have to implement an object that holds these two values:
var images = [];
function appendImage(src, text) {
images.push({
src: src,
text: text
});
}
Then create your 5 images like so:
appendImage('1.jpg', 'Picture 1');
appendImage('2.jpg', 'Picture 2');
appendImage('3.jpg', 'Picture 3');
appendImage('4.jpg', 'Picture 4');
appendImage('5.jpg', 'Picture 5');
Just make sure you have an element that's propely placed (using CSS) to fill with text
<div id="wrapper">
<img name="slide" alt="slide image">
<span id="sliderText"></span>
</div>
The change to your changeImg function will be minor, you just need to consider the new data structure.
var sliderText = document.getElementById('sliderText');
function changeImg(){
document.slide.src = images[i].src;
sliderText.innerHTML = images[i].text;
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
You can use javascript objects:
var i = 0;
var images = [];
var time = 3250;
// Image List
images[0] = {
url: 'http://via.placeholder.com/120x120',
caption: '120x120'
};
images[1] = {
url: 'http://via.placeholder.com/130x130',
caption: '130x130'
};
images[2] = {
url: 'http://via.placeholder.com/140x140',
caption: '140x140'
};
images[3] = {
url: 'http://via.placeholder.com/150x150',
caption: '150x150'
};
images[4] = {
url: 'http://via.placeholder.com/160x160',
caption: '160x160'
};
// Change Image
function changeImg() {
document.slide.src = images[i].url;
caption.innerText = images[i].caption;
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#wrapper {
width: 800px;
height: 400px;
margin: 50px auto;
}
<h1>JS Slider </h1>
<div id="wrapper">
<img name="slide" alt="slide image">
<div id="caption">2134234</div>
</div>
jsfiddle
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>
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>