How to change img src after some time? - javascript

There's an img element with a certain src. I want to change the src after let's say 1000ms and then another after 1000ms and then stop at the last image. Is that possible in jQuery, with delay() maybe?

Place the image paths in an array. Then, using a timer (setInterval() or setTimeout()), you change the source of the image with the next item in the array until you've reach the end.
Anything you can do with vanilla JavaScript can be done with JQuery, but JQuery is way overused and for something this simple, would be overkill.
var paths =
[ "https://www.spreadshirt.com/image-server/v1/mp/designs/12386804,width=178,height=178/winking-smiley-face.png",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTUirw89Ct-tBfgNgrCV8ygX65aomMvVbr1LsEgnaH8eJBG3FZH",
"https://www.energylivenews.com/wp-content/uploads/2014/06/Smiley-face-emoticon-575.jpg"];
var img = document.getElementById("img");
var i = 0;
var timer = setInterval(function(){
// If we've reached the end of the array...
if(i >= paths.length){
clearInterval(timer); // Stop the timer
return; // Exit the function
}
img.src = paths[i++]; // Sete the path to the current counter and then increase the counter
}, 1000);
img {
width:200px;
}
<img id="img">

For an infinite loop change the code above to:
var img = document.getElementById("img");
var i = 0;
var timer = setInterval(function(){
// If we've reached the end of the array...
if(i >= paths.length){
i=0;
}
img.src = paths[i++]; // Sete the path to the current counter and then increase the counter
}, 1000);

Related

Rotating several images with different timings

I have three images side by side, left, middle and right. I want the first image on the left to change after 2 seconds, then the one in the middle to change 2 seconds later and then the one on the right to change 2 seconds after that. Then after another 2 seconds I want the first one on the left to change again and for the sequence to start all over again.
I've put together the javascript code for each image to have a certain start time and then a 6 second interval before changing again, this gives the effect I'm looking for.
The sequence works the first time round but when the first image is due to run through the sequence the second time round the whole thing seems to stick a bit and then all the images start changing together, as if they are all affecting one another. I don't know why this is since the code refers to each separately. Any help would be appreciated. Here's the code:
HTML Code:
<div>
<img id="mainImage" src="firstimage.jpg">
<img id="mainImage1" src="secondimage.jpg">
<img id="mainImage2" src="thirdimage.jpg">
</div>
Javascript Code:
<script>
var myImage = document.getElementById("mainImage");
var imageArray = ["image1.jpg","image2.jpg","image3.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setTimeout(changeImage, 0000);
setInterval(changeImage,6000);
</script>
<script>
var myImage1 = document.getElementById("mainImage1");
var imageArray1 = ["image4.jpg","image5.jpg","image6.jpg"];
var imageIndex1 = 0;
function changeImage1() {
myImage1.setAttribute("src",imageArray1[imageIndex1]);
imageIndex1++;
if (imageIndex1 >= imageArray1.length) {
imageIndex1 = 0;
}
}
setTimeout(changeImage1, 2000);
setInterval(changeImage1,6000);
</script>
<script>
var myImage2 = document.getElementById("mainImage2");
var imageArray2 = ["image7.jpg","image8.jpg","image9.jpg"];
var imageIndex2 = 0;
function changeImage2() {
myImage2.setAttribute("src",imageArray2[imageIndex2]);
imageIndex2++;
if (imageIndex2 >= imageArray2.length) {
imageIndex2 = 0;
}
}
setTimeout(changeImage2, 4000);
setInterval(changeImage2,6000);
</script>
Solution:
For each
setTimeout(changeImage2, x);
setInterval(changeImage2,6000);
change to
setTimeout(function() {
setInterval(changeImage2,6000);
}, x);
Check here: https://jsfiddle.net/bstd3fqu/4/
Explanation:
setTimeout() doesn't make runtime to sleep for certain time. It simply set a timer to execute the mentioned function after certain time. So all setInterval() calls are executing at almost same time in your implementation. I am just setting the interval in the setTimeout function so that these setInterval() calls are executing at different times.

jQuery fade function with setInterval function

I'm creating simple slide with jQuery and its work fine i just want to use fade function as well with below code. I used fade function but it's working it's not fading an image while change.
var mainImage = $('#mainImage');
var imageData = ['_images/gallery/beach_houses.jpg','_images/gallery/golden_gate.jpg','_images/gallery/red_rock_01.jpg'];
var imageIndex = 0;
function imageSlide(){
mainImage.fadeIn("slow",function(){
mainImage.attr("src",imageData[imageIndex]);
imageIndex++;
if(imageIndex >= imageData.length){
imageIndex = 0;
}
});
}
setInterval(imageSlide,1000);
You've used fadeIn already, but in order for the image fade in it has to be hidden, the easiest way is to fade it out first.
Using the fadeOut callback, you can wait for the fadeOut to complete, set the src and then fadeIn:
var mainImage = $('#mainImage');
var imageData = ['_images/gallery/beach_houses.jpg','_images/gallery/golden_gate.jpg','_images/gallery/red_rock_01.jpg'];
var imageIndex = 0;
function imageSlide() {
// fade out before changing src
mainImage.fadeOut("fast", function(){
mainImage.attr("src",imageData[imageIndex]);
imageIndex++;
if(imageIndex >= imageData.length){
imageIndex = 0;
}
// fade back in after changing src
mainImage.fadeIn("slow");
});
}
// Increase interval to provide enough time if needed
setInterval(imageSlide, 1000);
Note that "slow" = 600ms so 2x slow (fade out then in) will be longer than your setInterval of 1000ms and will create some crazy results.
See my code follow 3 step, hope this can help you!
You need hide mainImage before use fadeIn
You need find target image source and set to mainImage
When you got all data needed, you can fadeIn your image at this step
Note: Index of the last item in your array is imageData.length - 1, reset imageIndex to zero here
var mainImage = $('#mainImage');
var imageData = ['http://www.vincenzo.net/isxkb/images/a/a9/Example.jpg','http://www.buzzlinestravel.co.uk/images/itinerary/1-1276781550ufzx.jpg','http://images.all-free-download.com/images/wallpapers_large/poppies_and_coreopsis_wallpaper_flowers_nature_wallpaper_1542.jpg'];
var imageIndex = 0;
function imageSlide(){
//1. you need hide before use fadeIn
mainImage.hide();
//2. you need find target source to show
mainImage.attr("src",imageData[imageIndex]);
imageIndex++;
if(imageIndex === imageData.length - 1){
imageIndex = 0;
}
//3. the last step, you got all data needed, you can fadeIn your image here
mainImage.fadeIn("slow");
}
setInterval(imageSlide,1000);
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script><!DOCTYPE html>
<html>
</head>
<body>
<img src="" alt="" id="mainImage">
</body>
</html>
Check the code below.For production purposes you still gonna have to 'polish' it.Good luck
var mainImage = $('#mainImage');
var imageData = ['https://www.maxcdn.com/blog/blog-assets/2016/01/firefox-subresource-integrity-error.png','https://www.typesettercms.com/data/_addondata/x_Addons/screenshots/5/245/thumbnail.png','https://cdn9.gaborszathmari.me/wp-content/uploads/2016/06/when-the-cdn-goes-bananas-cover.png'];
var imageIndex = 0;
function imageSlide(){
mainImage.attr("src",imageData[imageIndex]).fadeIn(1000,function(){
imageIndex++;
if(imageIndex >= imageData.length){
imageIndex = 0;
}
setTimeout(function(){
mainImage.fadeOut(1000,function(){
imageSlide();
});
},1000);
});
}
imageSlide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img style="display:none;" id="mainImage">

Transition in Slideshow not working

Today I managed to create a slideshow in javascript that has a fancy transparent transition, however, my problem is that after it reproduces the first 2 images, the next ones won't appear, and the slideshow repeats the second picture over and over again.
I've tried a few methods that did not work at all.
Any help and insight to the problem will be very important to me!
Here is a link to my code: eBRabp
My Javascript code:
// JavaScript Document
var myImage = document.getElementById('mySlide');
var imageArray = ["images/slider1.jpg","images/slider2.jpg","images/slider3.jpg","images/slider4.jpg","images/slider5.jpg","images/slider6.jpg","images/slider7.jpg"];
var imageIndex = 0;
function changeImage() {
mySlide.className = 'hiding';
setTimeout(function() {
mySlide.setAttribute('src', 'images/slider2.jpg','images/slider3.jpg','images/slider4.jpg','images/slider5.jpg','images/slider6.jpg','images/slider7.jpg' + imageArray[imageIndex] + '.jpg');
mySlide.className = 'showing';
}, 1000);
imageIndex++;
if (imageIndex == imageArray.length) imageIndex = 0;
}
var intervalHandle = setInterval(changeImage, 3000);
Problem is in: mySlide.setAttribute... line... It will not work, of course, because you have placed too much (wrong) arguments. You need just two, and since you have array of images set, simple, do this:
mySlide.setAttribute('src', imageArray[imageIndex]);
And it should work:
https://jsfiddle.net/9pd4hnyn/

JSFiddle Slider code not working in browser

I'm a little lost. I have used this JSFiddle code regarding a solution to my problem. http://jsfiddle.net/f8d1js04/2/ (thank you MartinWebb) - and the question(for context) is posed here; Add Fade Effect in Slideshow (Javascript) - MartinWebb's solution is towards the bottom.
Essentially I am rendering a slider onto the page. Now when I put random image links into the imgArray on the JSFiddle, it behaves perfectly. However, when I do it on my page and in my files (in the dom), after the last image, there is a gap - time w/ no image showing, and then it continues to run. How do I get rid of this momentary gap?
Also any ideas on what could be causing this to happen on the browser instead of the JSFiddle?
Sincerely thank you for any help & assistance!
var curIndex = 0,
imgDuration = 3000,
slider = document.getElementById("slider"),
slides = slider.childNodes; //get a hook on all child elements, this is live so anything we add will get listed
imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'];
//
// Dynamically add each image frame into the dom;
//
function buildSlideShow(arr) {
for (i = 0; i < arr.length; i++) {
var img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
// note the slides reference will now contain the images so we can
access them
}
//
// Our slideshow function, we can call this and it flips the image instantly, once it is called it will roll
// our images at given interval [imgDuration];
//
function slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
// first we start the existing image fading out;
fadeOut(slides[curIndex]);
// then we start the next image fading in, making sure if we are at the end we restart!
curIndex++;
if (curIndex == slides.length) {
curIndex = 0;
}
fadeIn(slides[curIndex]);
// now we are done we recall this function with a timer, simple.
setTimeout(function () {
slideShow();
}, imgDuration);
};
// first build the slider, then start it rolling!
buildSlideShow(imgArray);
slideShow();

Simple loop for images

I'm trying to build a simple image slider (but using a fade effect). Every two seconds, the image should change to another image. At the end, it should call repeat_sponsor() again, to start over, so it becomes a loop.
I've written this (highly ineffective) code for 5 images. Turns out I'm going to need it for around 50 images. My editor just freezes when I add too much code.
I've tried using while-loops, but I just can't figure it out how to do this the right way.
Anyone who can help me with this?
function repeat_sponsor()
{
$("#sponsor2").hide();
$("#sponsor3").hide();
$("#sponsor4").hide();
$("#sponsor5").fadeOut("slow");
$("#sponsor1").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor2").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor3").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor4").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor5").fadeIn("slow", ...
(function (){
var cnt = 50; //set to the last one...
var max=50;
function show() {
$("#sponsor" + cnt).fadeOut("slow"); //if you want the fadeout to be done before showing next, put the following code in the complete callback
cnt++;
if(cnt>max) {
cnt=1;
}
$("#sponsor" + cnt).fadeIn("slow");
window.setTimeout(show, 2000);
}
show();
})();
But the real issue is the fact you are loading tons of images from the start. You will be better off changing it so you only have a small subset of images and change the source.
You should use some sort of for loop and a class for hiding the images. and add a max value that if checks out resets c & i
var i=0;
var c=1;
function repeat_sponsor()
{
$("#sponsor"+i).fadeOut("slow");
$(".sponsers").hide()
$("#sponsor"+c).fadeIn("slow", function() {
window.setTimeout(repeat_sponsor(), 3000);
}
i++;
c++;
}
Just run a function every two seconds with setInterval and appropriately target your different sponsor divs:
var i = 1;
var max = 50;
setInterval(function() {
// Could target all other sponsor images with a class "sponsor"
$('.sponsor').fadeOut();
// Execute code on the target
$("#sponsor" + i).fadeIn();
if (i === max) {
i = 0;
}
i++;
}, 2000);

Categories

Resources