fadeOut() function with setInterval - javascript

I'm trying to create a transition effect between images without success.
I'm using this code that works fine, unfortunately the images change without any effect.
var images = [
"https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
"https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
]
var imageHead = document.getElementById("image-head");
var i = 0;
setInterval(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
https://jsfiddle.net/vvwcfkfr/1/
I've try thousand of solution this week with fadeIn, fadeOut, without any success.
I'm looking to create a transition effect like the slider on the Ryanair's homepage.
Any suggestion? Thanks.

You can use something like transition: background-image 0.3s; in CSS to achieve fade between images, but they have to be the same size. Otherwise there will be also resizing animation.

how about jquery fade in fade out. https://jsfiddle.net/vvwcfkfr/121/
setInterval(function() {
$('#image-head').fadeOut("slow",
function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
$('#image-head').fadeIn("slow")
}
);
}, 2000);

Related

How to make background-image fade using JavaScript without jQuery?

I'm success to use pure JavaScript to make background images fade in/out, but (1)how to make background image show first and start to fade in/out without white part? (2) making background image stay in div block? stuck in here for a week.
I'm trying to using onload event and CSS background-image but both don't work, CSS will make image keep stay in there.
HTML:
<div id="fade"> <span class="bg">Front-Learning</span> </div>
JavaScipt: (before)
var bgslide = [
'image/rotate-img-1.jpg',
'image/rotate-img-2.jpg',
'image/rotate-img-3.jpg'
];
bg_len = 0;
backgroundSlideshow = function bg1() {
if (bg_len == bgslide.length) bg_len = 0;
document.body.style.backgroundImage = 'url(' + bgslide[bg_len++] + ')';
document.body.style.backgroundRepeat ="no-repeat";
document.body.style.backgroundSize = "cover";
document.body.style.backgroundPosition ="center";
document.body.style.height = "400 px";
document.body.style.minWidth = "1000px";
}
window.setInterval(backgroundSlideshow,3000);
window.backgroundImage='url(' + bgslide[0] + ')';
window.onload = document.body.style.backgroundImage='url(' + bgslide[be_len] + ')';
JavaScript (after); it works and what I expect for, but I don't know what the different.
bg_len = 0;
backgroundSlideshow = function () {
if (bg_len == bgslide.length) bg_len = 0;
let fade=document.getElementById("fade");
fade.style.backgroundImage = 'url(' + bgslide[bg_len++] + ')';
}
window.setInterval(backgroundSlideshow,3000);
window.onload = backgroundSlideshow;

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

Change the background of a div with jquery easing the process

I was looking for a way to change the background of a div using jQuery and I found this question:
change background image jquery
I made it and it's working. But, there's a way to ease the process? Like an fade-in/out?
Sorry for my english. And thank you for your time.
UPDATE:
.branding{
min-height:530px;
background-image:url(../images/brandings-0.jpg);
background-repeat:no-repeat;
background-position:center;
}
var newBg = [
'site/assets/images/brandings-1.jpg',
'site/assets/images/brandings-2.jpg',
'site/assets/images/brandings-3.jpg'];
var i = 0;
var rotateBg = setInterval(function(){
i++;
if(i > 2)
i=0;
$('.branding').css({backgroundImage : 'url(' + newBg[i] + ')'});
}, 5000);
<div class="branding"></div>
Try the following fiddle I created for you.
http://jsfiddle.net/ujyjcfea/1/
var i = 0;
var newBg = [
'http://lorempixel.com/output/animals-q-c-640-480-2.jpg',
'http://lorempixel.com/output/animals-q-c-640-480-1.jpg',
'http://lorempixel.com/output/animals-q-c-640-480-4.jpg'];
var image = $('.branding');
image.css('background-image', 'url(http://lorempixel.com/output/animals-q-c-640-480-2.jpg)');
setInterval(function () {
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + newBg[i++] + ')');
image.fadeIn(1000);
});
if (i == newBg.length)
i = 0;
}, 5000);
http://www.programming-free.com/2013/12/change-background-image-jquery.html
demo - http://jsfiddle.net/victor_007/RyGKV/643/
var i = 0;
var images = ['http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-2.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg'];
var image = $('#slideit');
image.css('background-image', 'url(http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg)'); //Initial Background image setup
setInterval(function () {
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1000);
});
if (i == images.length) i = 0;
}, 5000);

Change background image on pagescroll to create animation? Is canvas more efficient?

I am working on a parallax site in which there are sequence of images (around 400 images). The background images change based on page scroll to create a smoothly moving animation. I managed to get the scrolling working, but when the user scrolls, the change of background images are not smooth (We can see the blank space for a second or so depending on the internet connection). Also, the images are not being cached, the page does a new request every time. How can I optimize this code so that the animation is smooth and it doesn't request a new image every time and uses the cached images. Is it efficient to create the animation in canvas? I tried canvas, but it also makes a new request to images on every scroll. Here is my code using standard background changing based on page scroll:
HTML
<div class="container">
<div id="background-images" class="background-images">
<div class="test"></div>
</div>
</div>
CSS
#background-images{
height: 4000px;
}
.container{
border: 1px solid red;
height: 400px;
overflow: auto;
}
.test{
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 600px;
height: 600px;
}
Javascript
var $container = $(".container");
var $bgImage = $(".test");
// Attaching the scroll to the background image
$container.scroll(function(event) {
var position = $container.scrollTop();
setBgImage(position);
});
// preload the given total amount of iamges
function preload(totalImages) {
for (var i = 0; i < totalImages; i++) {
$('<img/>')[0].src = getImgUrl(i);
}
}
preload(36); // Preload 36 images, the cache should keep these so we wont't need to load these while we scroll
// Set the background image
function setBgImage(position){
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + ", Position: " + position);
$bgImage.css("background-image", "url('" + getImgUrl(imageNum) + "')");
}
// Set a placeholder background image
function getImgUrl(num){
return "http://placehold.it/200x200/&text=" + num;
}
JSFiddle: http://jsfiddle.net/4j9u8qtf/1/
You could add all the images hidden and just show the correct one in an actual image element, instead of using css background image. I edited your jsfiddle to demonstrate:
function create(totalImages) {
for (var i = 0; i < totalImages; i++) {
var img = $('<img/>')
img[0].src = getImgUrl(i);
$bgImage.append(img)
}
setBgImage(0)
}
create(37);
function setBgImage(position){
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + ", Position: " + position);
$bgImage.find("img").hide().eq(imageNum).show()
}
http://jsfiddle.net/y92g7vvL/1/
The best way to preload images is to use the Image constructor like the example below. Using the Image constructor makes it so you don't have to worry about attaching the images anywhere to the document to make them load.
function preload(url) {
var image = new Image();
image.src = url;
}
I updated your Fiddle to use this preload and to not use jQuery for setting the background-image. It works quite well now. All images are preloaded/loaded only once.
$(function () {
var $container = $(".container");
var $bgImage = $(".test");
var bgImage = $bgImage.get(0);
$container.scroll(function (event) {
var position = $container.scrollTop();
setBgImage(position);
});
// preload the given total amount of iamges
function preload(totalImages) {
function fetch(url) {
var image = new Image();
image.src = url;
}
for (var i = 0; i < totalImages; i++) {
fetch(getImgUrl(i));
}
}
preload(36);
function setBgImage(position) {
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
var url = getImgUrl(imageNum);
bgImage.style.backgroundImage = "url('"+ url +"')";
}
function getImgUrl(num) {
return "http://placehold.it/200x200/&text=" + num;
}
})
Try
html
<div class="container">
<div id="background-images" class="background-images">
<div class="test"></div>
</div>
</div>
<!-- hidden container for `img` elements -->
<div id="imgs"></div>
css
#imgs {
display:none;
}
js
$(function () {
var $container = $(".container");
var $bgImage = $(".test");
$container.scroll(function (event) {
var position = $container.scrollTop();
setBgImage(position);
});
// preload the given total amount of iamges
function preload(totalImages) {
for (var i = 0; i < totalImages; i++) {
$('<img/>', {
"src": getImgUrl(i)
})
// append `img` elements to `#imgs` container
// to `cache` the images ,
// images not requested again at
// `$bgImage` `background-image` adjustments
.appendTo("#imgs");
}
}
preload(36);
function setBgImage(position) {
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + "
, Position: " + position
, $("#imgs img[src$=" + imageNum + "]"));
// utilize images already in DOM ,
// load `#imgs img` `src` as `$bgImage` `background-image` ,
// from hidden `#imgs` `div`
// images _not_ requested again from server ,
// see `network` tab at console
$bgImage.css("background-image"
, "url('" + $("#imgs img[src$=" + imageNum + "]").attr("src") + "')");
}
function getImgUrl(num) {
return "http://placehold.it/200x200/&text=" + num;
}
});
jsfiddle http://jsfiddle.net/guest271314/bh91g0tv/
The reason that they're being requested over and over is that you're using jQuery background assignment, which reloads the image.
This is silly. You don't need or want jQuery here, and it has side effects you don't understand that are causing your problem.
Just set the X position of the background. Done.
function offset_to(id, posX, posY) {
document.getElementById(id).style.backgroundPosition = posX.toString() + 'px ' + posY.toString() + 'px';
}
To create a smooth effect to your image transition just add css transition in your case:-
.test{
-webkit-transition: all 0.5s ease;
-moz-transition: position 10s;
-ms-transition: position 10s;
-o-transition: position 10s;
transition: all 0.8s ease;
}

Need Jquery chaning My Background image in a DIV

I`m starting level in jquery , but i have the concept of my idea , i have a #SlidShow div , all i need to change the css property ( background-image ) every 3 second , i have i think 4 image , so my concept is (( Make New Array with images link )) and change the .css( background-image ) of this div with this array every 3s ..
i hope that my concept be right :) , can any one help me with that
#('SlideShow').css('background-image', (Array /* Cant handle it */));
var array = ['url(a.png)', 'url(b.png)', 'url(c.png)', 'url(d.png)'];
var i = 0;
function setBackgroundImage() {
$('#SlideShow').css('background-image', array[i]);
i = i % array.length;
}
setBackgroundImage();
setInterval(setBackgroundImage, 3000);
You already got your answer. Just wanted to add that jQuery is a bit overkill if this is all you want to do, but it's probably not.
Here is a pure javascript solution:
http://jsfiddle.net/2BQV5/2/
var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];
window.onload = function ()
{
index = 0;
var c = document.getElementById('cat');
setInterval(function() {
if(index > arr.length-1) {index = 0}
c.style.backgroundImage='url(' + arr[index++] + ')';
}, 3000);
}
Have fun!
Edit
However for the second request in the comments, to have to pictures fade, jQuery is probably more suited.
Here is one way to achieve the fading effect:
http://jsfiddle.net/8jWT5/
var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];
$(document).ready(function() {
var c = $('#cat');
fade = document.createElement('div');
$(fade).attr('style','position: absolute; width:' + c.width() + 'px; height:' + c.height() + 'px;').attr('id','fade').hide();
c.append(fade);
var index = 0;
setInterval(function () {
$('#fade').css('background-image', 'url(' + arr[index] + ')').fadeIn(500,function() {
c.css('background-image', 'url(' + arr[index++] + ')');
if(index > arr.length-1) {index = 0}
$(this).hide();
});
}, 3000);
});

Categories

Resources