Image change every 30 seconds - loop - javascript

I would like to make an image change after 30 seconds. The javascript I'm using looks like this:
var images = new Array();
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
var x = 0;
function changeImage() {
document.getElementById("img").src=images[x];
x++;
}
HTML:
<img id="img" src="startpicture.jpg">
Now I haven't tested this one yet, but if my calculations are correct it will work :)
Now what I also want is to make a "fading transition" and I would like the changing of images to loop (it restarts after all the images have been shown).
Do any of you guys know how to do that?

I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);

You should take a look at various javascript libraries, they should be able to help you out:
mootools
jQuery
Dojo Toolkit
prototype
All of them have tutorials, and fade in/fade out is a basic usage.
For e.g. in jQuery:
var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
$img.fadeOut(speed, function() {
$img.attr("src", images[(++i % images.length)]);
$img.fadeIn(speed);
});
}, 30000);

setInterval function is the one that has to be used.
Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);

Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">

Related

How can I make the slideshow stop? And what ways can I improve the code?

I have a slideshow that (for testing purposes) swipes through every 1 second. I have it to stop when it gets back to the first image. But when it stops on it and I click on the next button nothing happens. And when I do mess with it it will start swiping through again.
I've tried while statements but that's really it.
My code:
var i = 0;
var images = [];
var time = 1000;
images[0] = 'michael-baird-14942-unsplash.jpg';
images[1] = 'kees-streefkerk-352781-unsplash.jpg';
images[2] = 'hakon-sataoen-1484216-unsplash.jpg';
images[3] = 'mario-silva-1492028-unsplash.jpg';
images[4] = 'will-turner-1474611-unsplash.jpg';
function changeImg() {
document.slide.src = images[i];
if (i < images.length) {
i++;
} else if (i > 4) {
document.slide.src = images[0];
} else {
i = 0;
}
if (i == 0) {
$('.next').on('click', function() {
i++;
});
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
.slideshow {
width: 100%;
height: 75%;
position: absolute;
top: 42px;
}
.slideshow img {
object-fit: cover;
width: 100%;
height: 100%;
}
<div class="slideshow">
<img name="slide" alt="Slideshow Images" width="100%" height="100%">
<a class="next">❯</a>
<a class="prev">❮</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="masterjs.js" charset="utf-8"></script>
As you can see in the JavaScript it goes through and stops at the first image. But as you can also see that this isn't a very good way to do this. If you guys can can you try to keep it in JavaScript/jQuery? If not or there is a better way please post it. But basically because of the way that it is it cycles through stops at the beginning and stays but if you mess with it VIA the next button it causes it to restart. I basically want it to cycle through the images and then stop at the beginning allowing the user to then cycle through them themselves. Also I want to add animations between images that's why I am asking for other ways that may be better for that too.
The issue is with this condition:
else if (i > 4) {
document.slide.src = images[0];
}
Your image updates to the first element of the images array, and your counter stops incrementing. Try mentally running through your code while keeping track of the value of i. Once this condition is met, does it ever stop being met?
The solution is simple, just reset the value of i when you reset the image:
else if (i > 4) {
document.slide.src = images[0];
i = 0;
}
You may then run into issues with your event listener as it triggers when i == 0, and therefore will be triggered when i is reset as above. There are some good reasons to use i === 0 instead, I recommend looking into it!
In addition, you should consider using a array.push() to add to the images array.
Finally I'd also recommend using console.log() as a way to keep track of what your code is actually doing -- this should aid in the debugging process.
Refer Below javascript code
<script type="text/javascript">
var i = 0;
var firstSlide = 0;
var images = [];
var time = 1000;
images[0] = 'https://i.ytimg.com/vi/SiVr9DM_EG0/maxresdefault.jpg';
images[1] = 'https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png';
images[2] = 'https://files.brightside.me/files/news/part_41/419860/18057510-1549810-23-0-1513767199-1513767212-650-1-1513767212-650-ce9f862cd3-1513864405.jpg';
images[3] = 'http://ichef.bbci.co.uk/news/999/mcs/media/images/80286000/png/_80286528_penisvagina.png';
images[4] = 'https://d345cba086ha3o.cloudfront.net/wp-content/uploads/2015/12/Chota-Bheem-Aur-Krishna-Drawing-e1451484119715.jpg';
function changeImg() {
if (i <= images.length && firstSlide == 0) {
document.slide.src = images[i];
if (i < images.length) {
i++;
} else if (i > 4) {
document.slide.src = images[0];
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
}
$('.next').on('click', function() {
firstSlide = 1;
i++;
var ind = (i % 5);
document.slide.src = images[ind];
});
$('.prev').on('click', function() {
firstSlide = 1;
i--;
var ind = (i % 5);
document.slide.src = images[ind];
});
window.onload = changeImg;
</script>

JavaScript load images with specific duration

I have two arrays : The first with images paths and the second is with different duration and I am trying using the following functions to set dynamically the 'setTimeout' of my 'changeImage()' function as follow:
function changeImage(){
var img = document.getElementById("img");
img.src = images[x];
var ztme = tme[x];
x++;
if(x >= images.length){
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()",ztme ); //This is the problem!
}
function fadeImg(el, val, fade){
if(fade === true){
val--;
}else{
val ++;
}
if(val > 0 && val < 100){
el.style.opacity = val / 100;
setTimeout(function(){fadeImg(el, val, fade);}, 10);
}
}
var images = [],
x = 0;
images[0] = "daki/eco_pic.jpg";
images[1] = "daki/art_tnt.gif";
images[2] = "daki/mkv_uk.jpg";
images[3] = "daki/bolo_trt.jpg";
images[4] = "daki/folo_fr.jpg";
var tme = [], //values of 'Time' for a picture to stay displayed
tme[0]= 10000;
tme[1]= 50000;
tme[2]= 2000;
tme[3]= 30000;
tme[4]= 5000;
setTimeout("changeImage()", 15000);
If I give a fixed number for the timeout everything is working like a charm. Therefore to set it dynamically generates just errors.
Any idea to let this changeImage() function get dynamically the time?
Am gratefull to any help.
Thank you in advance.
Your tme array is not properly initialized.you should used semi column after its declaration;
var tme = []; //<=
tme[0]= 10000;
tme[1]= 50000;
tme[2]= 2000;
tme[3]= 30000;
tme[4]= 5000;
setTimeout("changeImage()", 15000);

Javascript slideshow shows no image for one iteration

The slideshow shows pic1.jpg through pic8.jpg and then no image for 4 seconds and then starts back at pic1.jpg. I want it to go right back to pic1.jpg after pic8.jpg.
Here is my script:
<script>
var pics = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg"];
var i = 1;
function changeImage() {
var image = document.getElementById('homeslideshow');
if (i < pics.length) {
image.src = pics[i]
i++;
}
else {
image.src = pics[i]
i = 0;
}
}
</script>
The function is called in the html with:
<body onload="setInterval(function(){changeImage()}, 4000)">
And the slideshow is displayed with:
<div id="section">
<img id="homeslideshow" src="pic1.jpg" alt="goofy" width="100%" height=auto>
</div>
I am a total newbie to html/css/js, so please be nice! Any help would be much appreciated.
Replace your else block as below
else {
i = 0;
image.src = pics[i];
}
as in your code, when you was setting the image.src before setting the value of i to 0, actually you were setting the image src with pics[8] which was not valid.
Also, you are missing a ; after image.src = pics[i] in the if block.
UPDATE
Replace your JS as below to solve your 8 seconds problem
<script>
var pics = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg"];
var i = 0;
function changeImage() {
var image = document.getElementById('homeslideshow');
if (i < pics.length-1) {
i++;
image.src = pics[i];
}
else {
i = 0;
image.src = pics[i];
}
}
</script>
You use 4000ms delay. Remove that.
setInterval(function(){changeImage()})

Javascript changing an image within a div after a certain amount of time

I am currently making a web page with an image inside of a div tag. I wrote a script to change the image after a certain amount of time, and it works fine when I test the script alone, however; when I attempt to place the script within my web page, it does not change the image.
Here is the code for my script:
<!DOCTYPE html>
<html>
<body>
<script>
images = new Array;
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
setInterval( function() {
changeImage()
}, 5000);
x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if ( x < 8 ) {
x += 1;
} else if ( x = 9 ) {
x = 0;
}
}
</script>
<img id='ad' src="img.gif">
</body>
</html>
I have tested this script with the image inside of a div tag and it still works fine. When I put the same code into my web page, it does not work. Also note, the image file names are just examples. The images I am using are from photobucket, so I have very little control over what they are called. Any help I could get on this would be greatly appreciated.
You need to put your code inside window.onload = function() {}
var images = new Array();
images[0] = "img2.gif";
images[1] = "img3.gif";
images[2] = "img4.gif";
images[3] = "img5.gif";
images[4] = "img6.gif";
images[5] = "img7.gif";
images[6] = "img8.gif";
images[7] = "img9.gif";
images[8] = "img10.gif";
function changeImage() {
document.getElementById('ad').src = images[x];
if (x<8) {
x+=1;
}
else if (x===9) {
x=0;
}
}
window.onload = function() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
Edit
This code has been tested on my local machine and works.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var images = new Array();
for (var i = 2; i < 11; i++) {
images.push("img" + i + ".gif");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
document.getElementById('imgsrc').innerHTML = "<h1>" + images[x] + "</h1>";
if (x < 8) {
x += 1;
} else {
x = 0;
}
}
window.onload = function() {
setInterval(function () {
changeImage();
}, 1000);
}
</script>
</head>
<body>
<img id="ad" src="img.gif" />
<div id="imgsrc"><h1>img.gif</h1></div>
</body>
</html>
Here is a fiddle of the final code working. JSFiddle doesn't like window.onload for some reason, so I had to exclude it. This doesn't really demonstrate my point, but I thought I'd just include it anyway.
Your code works to change the image src in this fiddle: http://jsfiddle.net/snB2a/1/
Try to rename your variables images and x to longer names. What can happen is, if some other code in your page, or worse, some code in one of the script file you page references, use variable "x" without declare it locally, then it would actually modify your "x" variable.
Here is an example to demonstrate the problem:
function something()
{
for (x = 0; i < 10; x++)
dosomethingelse();
}
If the above function is called in your page, then it will overwrite your "x" variable. The following code is safe:
function something()
{
var x;
for (x = 0; i < 10; x++)
dosomethingelse();
}

Preloading set of images using jQuery

I have a set of images that are frames in an animation like: frame-1.jpg, frame-2.jpg and I have about 400 images.
What I want to do is preload these 400 images before the animation starts.
Usually when preloading images I use the following:
var images = [
'img/nav-one-selected.png',
'img/nav-two-selected.png',
'img/nav-three-selected.png',
'img/nav-four-selected.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
But in this instance, listing the images in the var isn't feasible, and I also wish to fire off the start animation once the images have all been loaded.
So far I have the following:
$spinner_currentFrame = 1;
$numFrames = 400;
function preloadImages() {
$($images).each(function() {
var image = $('<img />').attr('src', this);
});
startAnimation();
}
function startAnimation() {
$spinner_loadingAnim = setInterval(function () {
UpdateSpinner();
}, 140);
}
function UpdateSpinner() {
$spinner_currentFrame = $spinner_currentFrame + 1;
if($spinner_currentFrame > $numFrames) {
$spinner_currentFrame = 1;
}
console.log($spinner_currentFrame);
$('#spinner').css("background-image", "url(frame-" + $spinner_currentFrame + ".jpg)");
}
$(document).ready(function() {
preloadImages();
});
So the plan is that I preload images that are from 1 to 400 and then once that's completed then start the animation. How would I build the $images var though?
I've thought about something like:
$images = [];
$frame = 1;
$numFrames = 400;
$($frame).each(function() {
$frame = $frame + 1;
if($frame <= $numFrames) {
$images =+ 'frame-' + $frame + '.jpg';
}
});
But I'm not sure how a) efficient this is and b) how to do the callback once all images have loaded successfully.
You should use a standard javascript for loop instead of the jQuery's foreach. Foreach is wonderful for looping over an array or set of objects, but not in this case. Here is an example, please note that you have to bind the onload event handler before you set the Image object's src property.
UPDATE: added more functions to complete the entire example.
var loaded_images = 0;
var frames = 400;
var images = [];
function preloadImages() {
for (i=0; i < frames; i++) {
images[i] = new Image();
images[i].onload = function() {
loaded_images += 1;
checkLoadingFinished();
}
images[i].src = 'frame-' + i + '.jpg';
}
}
function checkLoadingFinished() {
if (loaded_images >= frames) {
startAnimation();
}
}
function startAnimation() {
var frameNumber = 0;
var timer = setInterval(function() {
$('#img-dom-element').attr('src', images[frameNumber]);
if (frameNumber > frames) {
frameNumber = 0;
else
frameNumber++;
}, (1000/30)); // (1000/30) = 30 frames per second
}
$(document).ready(function() {
preloadImages();
});
I dont know if it fits to your special case but I use
http://thinkpixellab.com/pxloader/
to preload images. You can add the paths and get one callback if all images are loaded. Afterwards you can start animation.

Categories

Resources