I have the following code:
Code:
$(document).ready(function(){
var header = $('body');
var backgrounds = new Array(
'url(/1.jpg)'
, 'url(/2.jpg)'
, 'url(/1.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 5000);
header.css('background-image', backgrounds[0]);
});
What can I add to the above code so there is a "smooth" transition between background images. I prefer not to use a plugin.
THANKS :)
You can fade it out, change the background and fade it back in:
function nextBackground() {
current++;
current = current % backgrounds.length;
header.fadeOut(200, function(){
header.css('background-image', backgrounds[current]);
header.fadeIn(200);
})
}
If you want to crossfade the slides, you can place a duplicate of the image on top and fade it out as the next slide changes underneath.
$(document).ready(function(){
var image = $('.wrap');
var fader = $('.fader');
var backgrounds = new Array(
'url(https://via.placeholder.com/480&text=Slide+1)'
,'url(https://via.placeholder.com/480&text=Slide+2)'
,'url(https://via.placeholder.com/480&text=Slide+3)'
);
var current = 0;
function nextBackground() {
// Change the background image while
// creating a duplicate of image and
// fade it out
fader.css('background-image', backgrounds[current]).fadeOut(function() {
fader.css('background-image', '').show();
});
current++;
current = current % backgrounds.length;
image.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 2000);
image.css('background-image', backgrounds[0]);
});
.wrap, .fader {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-size: contain;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="fader"></div>
</div>
Related
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 would like to create a little slider to change background-image of my div every seconds.
My code doesn't work for the moment, image is not changed. And ideally, i would like that the script run in infinite mode..
HTML
<div id="slidesPartenairesHome"></div>
CSS
#slidesPartenairesHome {
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
margin-left: 120px;
}
JS
$( document ).ready(function() {
var arrayOfPartenaires = [
"images/partenaires/a.png",
"images/partenaires/b.jpg",
"images/partenaires/c.jpg",
"images/partenaires/d.png",
"images/partenaires/e.png",
"images/partenaires/f.jpg",
"images/partenaires/g.jpg",
"images/partenaires/h.jpg",
"images/partenaires/i.png",
"images/partenaires/j.jpg",
"images/partenaires/k.jpg",
"images/partenaires/l.jpg"
];
for (var i=0; i<arrayOfPartenaires.length; i++) {
var currentPartenaireImg = arrayOfPartenaires[i];
$('#slidesPartenairesHome').animate({opacity: 0}, 'slow', function() {
$(this).css({'background-image': 'url("'+currentPartenaireImg+')'}).animate({opacity: 1});
});
}
});
You could use window.setinterval, you could also use setTimeout but setinterval is a litle bit more precise.
Example with setinteval:
window.setInterval(function(){
var url = getCurrent();
//start animation
$('#slidesPartenairesHome').delay( 500 ).fadeTo(500, 0.3, function()
{
$(this).css('background-image', 'url(' + url + ')');
}).fadeTo('slow', 1);
}, 1000);
// We start with index of 1 because we want to skip the first image,
// Else we would be replacing it with the same image.
var index = 1;
var arrayOfPartenaires = [
"http://yourdomain.com/images/partenaires/a.png",
"http://yourdomain.com/images/partenaires/b.png",
"http://yourdomain.com/images/partenaires/c.png"
];
function getCurrent(){
// We check if the index is higher than the ammount in the array.
// If thats true set 0 (beginning of array)
if (index > arrayOfPartenaires.length -1){
index = 0;
}
var returnValue = index;
index ++;
return arrayOfPartenaires[returnValue];
}
Note if you really want to change the image every 1 second the background will be changing very fast.
Fiddle
I hope this may help you
html
<div id="slidesPartenairesHome">
<div id="imags">
</div>
</div>
Css
#slidesPartenairesHome
{
margin-left: 120px;
}
#slidesPartenairesHome, #imags
{
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
}
Js
$(function () {
var arrayOfPartenaires = [
"http://fotos2013.cloud.noticias24.com/animales1.jpg",
"http://www.schnauzi.com/wp-content/uploads/2013/03/animales-en-primavera.jpg",
"https://johannagrandac.files.wordpress.com/2015/01/conejos.jpg",
"http://png-4.findicons.com/files/icons/1035/human_o2/128/face_smile.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/128/big-smile-icon.png",
"http://simpleicon.com/wp-content/uploads/smile-256x256.png"
];
var loaders = 0;
function cycleImages() {
var element = arrayOfPartenaires[loaders];
$("#imags").css({ 'background-image': 'url(' + element + ')' }).animate({ opacity: 1 }).hide().fadeIn("slow");
if (loaders < arrayOfPartenaires.length) {
loaders = loaders + 1;
if (loaders >= arrayOfPartenaires.length) {
loaders = 0;
}
}
else {
loaders = 0;
}
console.log(loaders, arrayOfPartenaires[loaders]);
}
cycleImages();
setInterval(function () { cycleImages() }, 3000);
});
jsFiddel Demo
The following code creates the effect when one image goes to white and then white is changed with another image (demo):
HTML:
<body>
<div class="page-bg" id="page-background1"></div>
<!-- <div class="page-bg" id="page-background2"></div> -->
</body>
JavaScript:
url = "http://example.com/picture.png";
$("#page-background1")
.animate({
opacity: 0
}, 'slow', function () {
$("#page-background1")
.css({
'background-image': 'url(' + url + ')'
})
.animate({
opacity: 1
});
});
But I would like to change one image directly with another (without white color in between), but with fadeOut/fadeIn effect. How should I do it? Looks like usage of the second div should help, but I can not find working solution.
Updated, I tried to apply Stacking elements with Z-index to get the desired effect. I also created a kind of "stack" of images where z-index is changed for the image that was hidden; the most recently hidden element is changed for a smaller z-index value in comparison to other images in the "stack". The code supports multiple images in the photos array, because it creates an individual div for each image.
var photos = [{
url: 'https://drscdn.500px.org/photo/97037403/m=900/d924fc03d69a82a604129011300916be'
}, {
url: 'https://drscdn.500px.org/photo/97037259/m=900/030e1598b7822cd6c41beb4c7a4e466d'
}, {
url: 'https://drscdn.500px.org/photo/97158643/m=900/4ae40d67ef546341111a32f5176694c8'
}];
//z-index, start value -1
//z-index can be either positive or negative value
//based on this answer http://stackoverflow.com/a/491105/2048391
var zIndex = -1;
//first foto in the array shown/hidden first
var visibleIndex = 0;
//initialize
//by creating div for each image/url
for (i = 0; i < photos.length; i++) {
var div = document.createElement("div");
div.id = "page-background" + (i + 1);
div.setAttribute("class", "page-bg");
div.style.zIndex = zIndex;
var url = "url('" + photos[i].url + "')";
div.style.background = "#505D6E " + url + " no-repeat center center fixed";
document.body.appendChild(div);
zIndex = zIndex - 1;
//and add div id to the photos array
photos[i].id = "page-background" + (i + 1);
}
function changeBackground() {
var hideItemIndex = visibleIndex % photos.length;
var showItemIndex = (visibleIndex + 1) % photos.length;
var hideItemId = "#" + photos[hideItemIndex].id;
var showItemId = "#" + photos[showItemIndex].id;
//hide current image with animation
//after which show the next image with animation
$(hideItemId).animate({
opacity: 0
}, "slow", function() {
$(showItemId)
.animate({
opacity: 1
}, "slow");
//change z-index for the item that was hidden
//by moving it to the bottom of the stack
$(hideItemId).css("z-index", zIndex);
$(hideItemId).css("opacity", 1);
});
zIndex = zIndex - 1;
visibleIndex = visibleIndex + 1;
}
//make sure that there's at least 2 images in the array
if (photos.length > 1) {
setInterval(function() {
changeBackground();
}, 2000);
}
.page-bg {
border: 1px solid black;
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Alternative way of doing the same thing as above. Below only visible and the next div element exist, and the hidden div is removed for performance reasons, like suggested by LA_
var photos = [{
url: 'https://drscdn.500px.org/photo/97037403/m=900/d924fc03d69a82a604129011300916be'
}, {
url: 'https://drscdn.500px.org/photo/97037259/m=900/030e1598b7822cd6c41beb4c7a4e466d'
}, {
url: 'https://drscdn.500px.org/photo/97158643/m=900/4ae40d67ef546341111a32f5176694c8'
}];
//z-index, start value 100000
//z-index could be a larger number
//based on this answer http://stackoverflow.com/a/491105/2048391
var zIndex = -1;
//first foto in the array shown/hidden first
var visibleIndex = 0;
//initialize
//by creating div for each image/url
for (i = 0; i < photos.length; i++) {
//only two images are created
if (i < 2)
createDiv(i, (i + 1) );
//and add div id to the photos array
photos[i].id = "page-background" + (i + 1);
}
function changeBackground() {
var hideItemIndex = visibleIndex % photos.length;
var showItemIndex = (visibleIndex + 1) % photos.length;
var hideItemId = "#" + photos[hideItemIndex].id;
var showItemId = "#" + photos[showItemIndex].id;
//hide current image with animation
//after which show the next image with animation
$(hideItemId).animate({
opacity: 0
}, "slow", function () {
$(showItemId)
.animate({
opacity: 1
}, "slow");
//remove the item that was hidden
$(hideItemId).remove();
});
var nextItemIndex = (visibleIndex + 2) % photos.length;
//create the next div with picture
createDiv(nextItemIndex, (nextItemIndex + 1) );
visibleIndex = visibleIndex + 1;
}
//make sure that there is at least 2 photos
if (photos.length > 1) {
setInterval(function () {
changeBackground();
}, 2000);
}
function createDiv(index, divIdNro) {
var div = document.createElement("div");
div.id = "page-background" + divIdNro;
div.setAttribute("class", "page-bg");
div.style.zIndex = zIndex;
var url = "url('" + photos[index].url + "')";
//div.style.backgroundImage = url;
div.style.background = "#505D6E " + url + " no-repeat center center fixed";
document.body.appendChild(div);
zIndex = zIndex - 1;
}
.page-bg {
border:1px solid black;
height:100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
here's a fiddle as snippets not working sat the mo, you can put the speed of the fade in milliseconds or keyword, it's at slow. I've left it on button click and not passed in the url but take out my button click function and put the code into your setinterval func, also set the url in jquery back to url variable
$('button').on('click',function(){
$("#page-background1").fadeOut( "slow", function() {
$("#page-background1")
.css({
'background-image': 'url(http://lorempixel.com/400/400/sports/2)'
});});
$("#page-background1").fadeIn('slow');
});
.page-bg{
min-width:500px;
min-height:500px;
}
#page-background1{
background-image: url(http://lorempixel.com/400/400/sports/1);
background-size:400px 400px;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me to change the background</button>
<div class="page-bg" id="page-background1">;</div>
Change the javascript to:
url = "http://example.com/picture.png";
.animate({
opacity: 0.5
}, 'fast', function () {
$("#page-background1")
.css({
'background-image': 'url(' + url + ')'
})
.animate({
opacity: 1
});
});
I am trying to dynamically change my background image by continuously looping through an array of image paths. The code works if I log the output to a console, but I cannot get the image to actually change.
Original CSS: (I am overriding the default style from another CSS file)
<style>
.jumbotron {
background: #7da7d8 url('images/rotunda2.jpg') no-repeat center center !important;
}
</style>
JavaScript:
$(document).ready(function () {
var count = -1;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
setInterval(swap, 5000);
function swap(){
$('.jumbotron').css("background", "#7da7d8 url('"+images[++count % images.length]+"') no-repeat center center !important");
console.log(images[++count % images.length]);
}
});
Any ideas?
You're swap function seems kind of odd. Typically for something like this, you could have a counter that gets incremented and then just resets to 0 and starts over. Also make sure you are running in an onload event handler context.
var count = 0;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
function swap(){
//get the next image
var nextImage = images[count];
console.log(nextImage);
$('.jumbotron').css("background-image", nextImage);
//increment count
count = count > images.length - 1 ? 0 : count+=1;
}
$(document).ready(function(){
setInterval(swap, 5000);
});
aside from that, make sure to check your error console for errors, and for 404's indicating you might have bad image paths
Try this:
$(document).load(function() {
var count = -1;
var images = ['images/image1.jpg', 'images/image2.jpg', 'images/image3.jpg'];
setInterval(swap, 5000);
function swap() {
var img = images[++count % images.length];
$('.jumbotron').css('background', '#7da7d8 url(' + img + ') no-repeat center center !important');
console.log(img);
}
});
I don't think change css is a good idea, you may define some classes, and dynamically change the classes on the element!
html:
<div class="dynamicBg class1"></div>
<div class="dynamicBg class1"></div>
css:
.dynamicBg {
background-color: #7da7d8;
background-repeat: no-repeat;
background-position: center center;
}
.class1 {
background-image: url('images/image1.jpg');
}
.class2 {
background-image: url('images/rotunda2.jpg');
}
.class3 {
background-image: url('images/rotunda3.jpg');
}
.class4 {
background-image: url('images/rotunda4.jpg');
}
js:
$(function() {
var classStr = 'class1 class2 class3 class4',
classArr = classStr.split(' '), i = 0,
$dynamicBg = $('.dynamicBg');
setInterval(function() {
i = i > 3 ? 0 : i + 1;
$dynamicBg.removeClass(classStr).addClass(classArr[i]);
}, 5000);
});
Wait for the document to load:
$(document).load(function()
{
var count = -1;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
setInterval(swap, 5000);
function swap(){
$('.jumbotron').css("background", "#7da7d8 url("+images[++count % images.length]+") no-repeat center center !important");
console.log(images[++count % images.length]);
}
});
http://jsfiddle.net/MAaVV/
Above is the JSFiddle for my code. It's some CSS to make an image full screen, and then a simple src change for the image. I want to change image backgrounds every 5 seconds. It's below as well:
<STYLE type=text/css>
#bg {
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
#bg img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
}
</style>
<script type="text/javascript">
for(var x = 0; x < 2; x++)
{
setTimeout(function()
{
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg","http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg","clf.jpg"];
document.getElementById("img").src = imgs[x];
},5000);
}
</script>
<div id="bg">
<img id="img" src="http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg?w=919&h=613" alt="" />
</div>
Anyone know why it isn't working?
Bonus points for building in a redirect (to another website) after the last image of the slideshow is shown for 5 seconds.
Try this:
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg", "http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg"];
var i=0;
setInterval(function () {
document.getElementById("img").src = imgs[i];
if(i==1)
{
//alert('test');
$("#img").click(function(){
alert('on');
location.href='http://www.google.com';
});
}
if(i++>=1) i=0;
}, 5000);
Fiddle: http://jsfiddle.net/MAaVV/6/
Your code fails for two reasons:
You set all three (or two in th case of the jsFiddle) timeouts to run at the same time. Your code sets all three to run 5 seconds after the call, but all the calls are made at the same time, so they'll all run 5 seconds later.
You use the x variable in your timeout function, but it is not defined in the scope for that function. So, in all cases, the image is getting 'undefined' as the src.
To fix this, I'd use something like this:
<script type="text/javascript">
var imageIndex = 0;
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg","http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg","clf.jpg"];
setInterval(function(){
document.getElementById("img").src = imgs[imageIndex++];
if(imageIndex >= imgs.length) imageIndex = 0;
},5000);
</script>
http://jsfiddle.net/MAaVV/5/
EDIT: To make the function do something after all the slides have shown, you might try something like this:
<script type="text/javascript">
var imageIndex = 0;
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg","http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg","clf.jpg"];
var interval = setInterval(function(){
document.getElementById("img").src = imgs[imageIndex++];
if(imageIndex >= imgs.length){
clearInterval(interval);
setTimeout(function(){
// do whatever you want here, after a 5 second pause
},5000);
},5000);
</script>
var imgs = ["http://www.hdwallpapers.in/walls/aprilia_rsv4_motorcycles-wide.jpg", "http://chivethethrottle.files.wordpress.com/2012/12/user-girl-motorcycle-920-3.jpg"];
var currentImage = 1;
$(document).ready(function(){
setInterval(function(){
if (currentImage >= imgs.length)
{
currentImage = 0;
window.location.href = 'http://www.google.com';
}
else
{
currentImage++;
}
$("#bg #img").attr("src", imgs[currentImage]);
}, 5000);
});
http://jsfiddle.net/MAaVV/2/