JQuery: How to change image after time with fadeIn? - javascript

I want to change an image automatically after 2000ms. The image should fade in.
My HTML:
<div class="nile-slider large-12 column">
<img alt="landing page 3" src="assets/Startseite/Slider/Slider_2.jpg">
</div>
My JS:
// change header image after 2 seconds
var images = ['Slider_1.jpg','Slider_2.jpg','Slider_3.jpg', 'Slider_4.jpg'],
index = 0, // starting index
maxImages = images.length - 1;
var timer = setInterval(function() {
var currentImage = images[index];
index = (index == maxImages) ? 0 : ++index;
$('.nile-slider img').attr('src','assets/Startseite/Slider/'+currentImage).fadeIn('slow');
}, 2000);
With this code the images changes but it does not fade in. How can I force the images to fade in (and even fade out)?

You can combine fadeOut and fadeIn() using fadeOut callback function, to achieve this.
// change header image after 2 seconds
var images = ['Slider_1.jpg','Slider_2.jpg','Slider_3.jpg', 'Slider_4.jpg'],
index = 0, // starting index
maxImages = images.length - 1;
var timer = setInterval(function() {
var currentImage = images[index];
index = (index == maxImages) ? 0 : ++index;
$('.nile-slider img').fadeOut(200, function() {
$('.nile-slider img').attr("src", 'assets/Startseite/Slider/'+currentImage);
$('.nile-slider img').fadeIn(200);
});
}, 2000);

Providing the new source as callback of fadeOut may do the trick:
$('.nile-slider img')
.fadeOut('fast',
function () {
$('.nile-slider img')
.attr('src','assets/Startseite/Slider/'+currentImage)
.fadeIn('slow');
}
);

Related

Animate background images within one data attribute

I try to create a nice animation between these background images urls, which are live in one data attribute (first image loads immediately, after 5 second the next images, after the next etc. After last one it starts from the beginning).
<div data-images="/media/jtjglhbb/main-bg-01.jpg,/media/u2bitolk/main-bg-02.jpg,/media/iasbuo5n/main-bg-04.jpg,/media/f00jm2va/main-bg-03.jpg,"></div>
var $dataImages = $('[data-images]');
var imagesList = $dataImages.data('images').split(',');
$.each(imagesList, function (index, value) {
setTimeout(function () {
$dataImages.stop().animate({ opacity: 0 }, 1000, function () {
$(this).css({ 'background-image': 'url(' + imagesList[index] + ')' })
.animate({ opacity: 1 }, { duration: 1000 });
});
}, 5000);
});
But it doesn't set up the first image, it only starts after 5 second and it runs altogether not one by one with 5 sec delay.
Obviously the logic is wrong, some help would be great.
Try like below. It should work.
image count will required to get mode value to start from beginning again.
index will hold index of image to show in background
changeImage function will be called recursively from inside so it will continuously update background.
use index = (index + 1) % imageCount; so index will start from 0 again from last index.
var $dataImages = $('[data-images]');
var imagesList = $dataImages.data('images').split(',');
// image count will required to get mode value to start from beginning again.
var imageCount = imagesList.length - 1;
// index of image to show in background
var index = 0;
// function will be called recursively from inside so it will continuously update background.
function changeImage() {
$dataImages.stop().animate({
opacity: 0
}, 1000, function() {
$(this).css({
'background-image': 'url(' + imagesList[index] + ')'
})
.animate({
opacity: 1
}, {
duration: 1000
});
});
// update index to next image url
index = (index + 1) % imageCount;
// declare timeout to call function after required time
setTimeout(changeImage, 5000);
}
changeImage();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div style="height: 150px;" data-images="https://www.w3schools.com/howto/img_nature_wide.jpg,https://www.w3schools.com/howto/img_snow_wide.jpg,https://www.w3schools.com/howto/img_lights_wide.jpg,https://www.w3schools.com/howto/img_mountains_wide.jpg"></div>

Adding fade function to JS script?

So I have this basic script which alternates between three images and I'd like to add a simple fadein/fadeout/fadeto or whatever looks best so it's not so clunky. How can I achieve this? Or, is there a better way?
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "assets/img/logo1.png";
images[1] = "assets/img/logo2.png";
images[2] = "assets/img/logo3.png";
You can set the opacity of the images before you change the src:
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
var imgvar = document.getElementById("img");
imgvar.classList.add("fadeOut");
setTimeout(function() {
imgvar.src = images[x];
imgvar.classList.remove("fadeOut");
}, 500);
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
var imgvar = document.getElementById("img");
imgvar.classList.add("fadeOut");
setTimeout(function() {
imgvar.src = images[x];
imgvar.classList.remove("fadeOut");
}, 500);
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "assets/img/logo1.png";
images[1] = "assets/img/logo2.png";
images[2] = "assets/img/logo3.png";
And in CSS:
img {
opacity: 1;
transition: opacity 500ms ease-in-out;
}
img.fadeOut {
opacity: 0;
}
Note: I added a 500ms timeOut in javascript because I suspect that otherwise the animation wouldn't be visible at all because it would instantly go from visible to invisible to visible again.
You could place two image elements in the page. One for the current image and one for the next image.
Once the time to show the image has passed, apply a CSS class on the visible image to transition its opacity to 0.
Once the transition is completed, replace the image source with the next image to show. Position the image element behind the image element that is now visible to the user and remove the transition CSS.
You can use the following. Source, W3 Schools. See here for the jQuery include
$(document).ready(function(){
$(".btn1").click(function(){
$("p").fadeOut()
});
$(".btn2").click(function(){
$("p").fadeIn();
});
});
However, this uses jQuery. Depending on your limitations, you may not be able to use this. For further information on both the fadeIn(time) and fadeOut(time) functions, checkout W3's article!
You can try animate.css to animate the html tag every time you call one of the functions.
https://github.com/daneden/animate.css

Javascript array is not recognizing called variable

function slideShow() {
var pageSplash = document.getElementById('splash');
var image = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
var i = 0;
while (i <= image.length) {
if (i > image.length) {
i = 0;
}
i += 1;
pageSplash.innerHTML = '<img id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + image[i] + '">';
setTimeout('slideShow', 5000);
}
}
I'm unsure why my i variable is not being recognized as the i variable from the rest of the function, so when ever I try to run my while loop it get's an error message saying that it's undefined.
I think you want setInterval instead of setTimeout, and you want you be careful that you increment i after you you update innerHTML.
function slideShow() {
var pageSplash = document.getElementById('splash');
var image = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
var i = 0;
setInterval(function () {
if (i === image.length) {
i = 0;
}
pageSplash.innerHTML = '<img id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + image[i] + '">';
i++;
}, 5000)
}
slideShow();
You don't need a while loop. You don't need to reset i. You don't need to set innerHTML.
Click Run code snippet... to see how this works. More explanation below the code
function slideShow(elem, images, delay, i) {
elem.src = images[i % images.length];
setTimeout(function() {
slideShow(elem, images, delay, i+1);
}, delay);
}
// setup slideshow 1
slideShow(
document.querySelector('#slideshow1 img'), // target element
[ // array of images
'http://lorempixel.com/100/100/animals/1/',
'http://lorempixel.com/100/100/animals/2/',
'http://lorempixel.com/100/100/animals/3/',
'http://lorempixel.com/100/100/animals/4/',
'http://lorempixel.com/100/100/animals/5/',
'http://lorempixel.com/100/100/animals/6/'
],
1000, // 1000 ms delay (1 second)
1 // start on slide index 1
);
// setup slideshow 2
slideShow(
document.querySelector('#slideshow2 img'), // target element
[ // array of images
'http://lorempixel.com/100/100/nature/1/',
'http://lorempixel.com/100/100/nature/2/',
'http://lorempixel.com/100/100/nature/3/',
'http://lorempixel.com/100/100/nature/4/',
'http://lorempixel.com/100/100/nature/5/',
'http://lorempixel.com/100/100/nature/6/'
],
500, // 500 ms delay
1 // start on slide 1
);
#slideshow1, #slideshow2 {
width: 150px;
display: inline-block;
}
<div id="slideshow1">
<h2>Animals</h2>
<p>(1000 ms delay)</p>
<!-- initial image -->
<img src="http://lorempixel.com/100/100/animals/1/">
</div>
<div id="slideshow2">
<h2>Nature</h2>
<p>(500 ms delay)</p>
<!-- initial image -->
<img src="http://lorempixel.com/100/100/sports/1/">
</div>
This is a huge improvement because your slideshow function is reusable. It means you can use the same function for any slideshow you want. You can even run multiple slideshows on the same page, as I have demonstrated here.
As others have pointed out, the while loop is unnecessary and, as I pointed out, the setTimout was incorrectly written. The following simplifies your code significantly:
var i = 0;
function slideShow() {
var pageSplash = document.getElementById('splash');
var imageArray = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
if(i < imageArray.length) {
pageSplash.innerHTML = '<img title='+ imageArray[i] + ' id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + imageArray[i] + '">';
}
i++;
}
setInterval(slideShow, 2000);
See: https://jsfiddle.net/dauvc4j6/8/ for a working version.
setTimeout calls the function again so you're re-initializing i to 0 every time you call it. Since you can use setTimeout to call the function recursively you don't need the while loop. Pull i out of the function altogether and make it a global variable.
//i should be global
var i = 0;
function slideShow() {
var pageSplash = document.getElementById('splash');
var image = ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"];
if (i >= image.length) {
i = 0;
}
i += 1;
pageSplash.innerHTML = '<img id ="splashImage" src="file:///C:/JonTFS/JonGrochCoding/Javascript%20Practical%20Test/' + image[i] + '">';
//set timeout is going to call slideShow again so if it's in the function it will call recursively, if you wanted to stop after a certain point you could nest setTimeout in an if
setTimeout(slideShow, 5000);
}
//you need to initially call the function
slideShow();

Javascript show imgs one by one with interval

I have the below images and I'm trying to show them one by one by interval of 3 seconds, but I am not able to get it work. It continues to stay on 0 and does not show the image, help would be nice:
<img src="one.png"></img>
<img src="two.png"></img>
javascript :
window.animate = function(){
var timer = '';
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var timer = setInterval(function(){
alert(i);
imgs[i].style.display = 'block';
}, 3000);
if(i == imgs.length){
clearInterval(timer);
}
}
}
This might be what you're looking for:
window.animate = function(){
var imgs = document.getElementsByTagName('img');
var index = 0;
var timer = setInterval(function() {
// Hide all imgs
for (var i = 0; i < imgs.length; i++)
imgs[i].style.display = 'none';
// Display next img
imgs[index].style.display = 'block';
index++;
// Stop after all displayed.
if (index >= imgs.length)
clearInterval(timer);
}, 3000);
}
Here is one way to do it:
Fiddle: http://jsfiddle.net/aecuappp/
HTML:
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
<img src="http://placehold.it/350x150"></img>
JS:
var imgs = document.getElementsByTagName('img');
var interval = 3000;
for (var i = 0; i < imgs.length; i++) {
(function (index, time) {
setTimeout(function() {
imgs[index].style.display = 'block';
}, time);
} (i, interval));
interval = interval + 3000;
}
CSS:
img {
display: none;
}
Basically you can start interval at 0 if you want first image to show up immediately. And each time it adds 3 seconds to the timeout since these are all created roughly at the same time. I wrapped the setTimeout in an IIFE to give interval and index scope for when the timeout needs the values at the time we created the timeout.
Since these are essentially all timing out at the same time, you need to implement a callback pattern to your interval to trigger the next one, or you need to increase the interval per index; i.e. set the timer's interval to 3000*(i+1), which will effectively trigger the next one at the delay plus the previous delay. This does not account for the actual images load however. Additionally, I would consider using setTimeout since you only need to do this once.
var img = $('img.targets');
for (var i=0;i<img.length;i++) {
var duration = 3000;
setTimeout( function() {
// do dom work here
}, duration*(i+1));
}
You can accomplish this by queuing up some timeouts using setTimeout and then making sure you are correctly passing the value of i to the function within. You can do that easily by using forEach instead of a regular loop:
window.animate = function() {
var imgs = document.getElementsByTagName('img');
imgs.forEach(function(img, i) {
setTimeout(function() {
img.style.display = 'block';
}, (i + 1) * 3000);
});
};

jQuery called with setInterval isn't animating on first interval

I have two images stacked. With setInterval(), the top one fades away, exposing the second. Then the top image switches to the bottom's src while invisible, and becomes opaque again. The second image changes to the next image and waits for the setInterval() to fade the top image and do it all over again.
It all works great, except the first time around; There's no fade. What am I not seeing?
This happens on all firefox and chrome and I assume all others.
HTML
<script type="text/javascript">
setInterval('swapImage()', 5000);
var galleryCount = 3;
</script>
...
<img id="image" src="images/gallery/01.jpg" />
<img id="imagenext" src="images/gallery/02.jpg" />
Javascript
function swapImage(imageToFadeID)
{
$("#image").animate
(
{ "opacity": "0" },
"slow",
"linear",
changeImage()
);
};
var i = 1;
function changeImage()
//counter +1
{
i = i + 1;
//add "0" to image number "j" if less than 10.
if (i < 10)
{
var j = "0" + i;
}
else
{
j = i;
}
//change top image to match bottom
var topImage = document.getElementById("imagenext").src;
document.getElementById("image").src = topImage;
//make top image reappear
document.getElementById("image").style.opacity = '1';
//change out bottom image to next
var btmImage = "images/gallery/" + j + ".jpg";
document.getElementById("imagenext").src = btmImage;
//reset counter if at end
if (i > galleryCount - 1)
{
i = 0;
}
}
I looks like you're invoking changeImage instead of passing it as a callback to animate:
Wrong:
function swapImage(imageToFadeID)
{
$("#image").animate
(
{ "opacity": "0" },
"slow",
"linear",
changeImage() // <--- !!! Remove the parentheses from this line!
);
};
Right:
function swapImage(imageToFadeID)
{
$("#image").animate
(
{ "opacity": "0" },
"slow",
"linear",
changeImage
);
};

Categories

Resources