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
Related
I have a series of images I want to transition from 0 opacity to 1 opacity when they come into the view port. I have the viewport check part done and the adding classes, however I would like them to be on an interval, so once the first 3 images come into the view port they appear 1, 2, 3 every .5seconds or so. Instead of all 3 at the same time.
here's a JS fiddle of how it works currently
reveal();
function reveal() {
var reveal = document.querySelectorAll(".reveal");
window.onscroll = function() {
for(var i = 0; i < reveal.length; i++) {
if(checkVisible(reveal[i]) === true) {
reveal[i].classList.add("fade");
}
}
}
};
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= -200);
}
https://jsfiddle.net/u04sy7jb/
I've modified your code to add a transition-delay of an additional .5 seconds for each element after the first one, in each "group" that is revealed as you scroll. I left comments in the JavaScript so you can understand the changes.
Let me know if you have any questions!
Live demo:
reveal();
function reveal() {
var reveal = document.querySelectorAll(".reveal");
window.onscroll = function() {
// start a new count each time user scrolls
count = 0;
for (var i = 0; i < reveal.length; i++) {
// also check here if the element has already been faded in
if (checkVisible(reveal[i]) && !reveal[i].classList.contains("fade")) {
// add .5 seconds to the transition for each
// additional element currently being revealed
reveal[i].style.transitionDelay = count * 500 + "ms";
reveal[i].classList.add("fade");
// increment count
count++;
}
}
}
};
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= -200);
}
.container {
width: 100%;
height: 1200px;
background-color: orange;
}
.reveal {
display: inline-block;
width: 32%;
margin: 0 auto;
height: 400px;
background-color: pink;
border: 1px solid black;
opacity: 0;
}
.fade {
opacity: 1;
transition: 1s;
}
<div class="container">
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
<div class="reveal"></div>
</div>
You could be able to stick your reveal[i].classList.add("fade"); inside of a setTimeout that executes as a function of your ith element so they show up how you're describing. Here is an example of adding short function to add the class and using it in a setTimeout to make this happen, although you could change it up to meet any additional needs.
function reveal() {
var reveal = document.querySelectorAll(".reveal");
window.onscroll = function() {
for(var i = 0; i < reveal.length; i++) {
if(checkVisible(reveal[i]) === true) {
addMyFadeClass(reveal[i], i)
}
}
}
};
function addMyFadeClass(element, i) {
setTimeout(function() {
element.classList.add("fade");
}, i * 500)
}
You can also use :nth-child CSS selectors without the need to change the JS:
.reveal:nth-child(3n+1).fade {
opacity: 1;
transition: 1s;
}
.reveal:nth-child(3n+2).fade {
opacity: 1;
transition: 1.5s;
}
.reveal:nth-child(3n).fade {
opacity: 1;
transition: 2s;
}
JSFiddle: https://jsfiddle.net/u04sy7jb/8/
i have following script like :
/* jshint loopfunc:true */
var url = [
"http://protiumdesign.com/wp-content/uploads/2015/04/Material-Design-Background-1024.jpg",
"http://i.imgur.com/wt4NRqA.jpg",
"http://i0.wp.com/thezinx.com/wp-content/uploads/md-6.png"
];
$(document).ready(function() {
changeBack();
function changeBack() {
for (var i = 0; i < url.length; i++) {
$('#elem').fadeTo('slow', 0.3, function() {
$(this).css('background-image', 'url(' + url[i] + ')');
}).fadeTo('slow', 1).delay(1000);
}
changeBack();
}
});
the function above for change the background image dynamically but the array is undefined within the function, how to fix that , thank you
this is the fiddle : Here
Although one of the issues described here is a duplicate of JavaScript closure inside loops – simple practical example, there are other issues like infinite recursive call of changeBack.
I think a better approach will be
/* jshint loopfunc:true */
var url = ["http://protiumdesign.com/wp-content/uploads/2015/04/Material-Design-Background-1024.jpg", "http://i.imgur.com/wt4NRqA.jpg", "http://i0.wp.com/thezinx.com/wp-content/uploads/md-6.png"];
$(document).ready(function() {
var i = 0;
function changeBack() {
$('#elem').fadeTo('slow', 0.3, function() {
$(this).css('background-image', 'url(' + url[i++] + ')');
i = i < url.length ? i : 0
}).fadeTo('slow', 1).delay(1000).promise().done(changeBack);
}
changeBack();
});
#elem {
width: 500px;
height: 300px;
background-size: 100%;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='elem'></div>
I'm using the following code to run a slider. The function runs well.
How do I make a simple fadein effect with js. No jQuery.
Also setInterval waits 5 seconds before displaying the first image. How do I start with an image and then continue with the 5 second interval?
var i = 0;
var hello = function(){
if(i<image.length)
{document.getElementById('fullscreenImage').src = image[i];
i+=1;
}
else i = 0;
}
setInterval(hello,5000);
#fullscreenImage {
z-index: -999;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-size: cover;
}
<img id="fullscreenImage"></img>
You can do this by progressively adjusting the opacity style property of an image. Here's a simple example: declare some HTML structure, then wire the sliding behavior, using the makeSlider() function, passing an array containing the target images, as well as fading parameters.
HTML file example (whatever.html) :
<head>
<style type="text/css">
img {
position: absolute;
top: 0;
left: 0;
width: 300px;
visibility: hidden;
}
img:first-child {
visibility: visible;
}
</style>
<script type="text/javascript" src="slider.js"></script>
</head>
<body>
<img src="1.jpg" alt="Alt 1" />
<img src="2.jpg" alt="Alt 2" />
<script type="text/javascript">
var fadeInterval = 3000;
var fadeStep = 20;
setTimeout(function() {
makeSlider([document.images[0], document.images[1]], fadeInterval, fadeStep);
}, fadeInterval);
</script>
</body>
Javascript file (slider.js):
function makeSlider(pictures, fadeInterval, fadeStep) {
var currentIndex = 0;
function show() {
var nextIndex = (currentIndex + 1) % pictures.length;
var current = pictures[currentIndex];
var next = pictures[nextIndex];
fade(current, 1, -0.1, function() {
current.style.visibility = "hidden";
next.style.visibility = "visible";
fade(next, 0, +0.1, function() {
currentIndex = nextIndex;
setTimeout(function() { show(); }, fadeInterval);
});
});
}
function fade(element, origin, step, continuation) {
element.style.opacity = origin;
setTimeout(function () {
var nextOrigin = Math.round((origin + step) * 10) / 10;
if (nextOrigin >= 0 && nextOrigin <= 1) {
fade(element, nextOrigin, step, continuation);
} else {
continuation();
}
}, fadeStep);
}
show();
}
HTH.
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]);
}
});