I am wanting to change the background of a div every 3 seconds. This needs to loop round so once the last background image shows it loops back to the first one and so on and so on. I'm having trouble doing so.
I made a post previous to this which was VERY vague and didn't get help.
function animate() {
change1();
change2();
change3();
}
function change1() {
window.setInterval(function(){
$('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg)');$('.content').css('transition','background 1s linear');
},3000);
}
function change2() {
window.setInterval(function(){
$('.content').css('background-image','url(http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg)');$('.content').css('transition','background 1s linear');
},3000);
}
function change3() {
window.setInterval(function(){
$('.content').css('background-image','url(x)');$('.content').css('transition','background 1s linear');
},3000);
}
animate();
You totally overcomplicated this task. Just create an array with the URLs and a function that will set the slide URL, play the transition and set a variable that marks the next slide index. Then call this function with setInterval().
var currentIndex = 0;
var urls = [
'http://crondon.guko.co.uk/wp-content/uploads/2015/11/bride_groom_baronial_hall1.jpg',
'http://crondon.guko.co.uk/wp-content/uploads/2015/11/confetti.jpg',
'http://media.caranddriver.com/images/media/51/dissected-lotus-based-infiniti-emerg-e-sports-car-concept-top-image-photo-451994-s-original.jpg'
];
var length = urls.length - 1;
function slide() {
$('.content').css('background-image', 'url(' + urls[currentIndex] + ')');
$('.content').css('transition', 'background 1s linear');
currentIndex = (currentIndex < length) ? currentIndex + 1 : 0;
}
slide();
window.setInterval(slide, 3000);
.content {
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"></div>
Related
I have created a JavaScript Slideshow, but I don't know how to add the fade effect. Please tell me how to do it, and please tell in JavaScript only, no jQuery!
Code:
var imgArray = [
'img/slider1.jpg',
'img/slider2.jpg',
'img/slider3.jpg'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
Much shorter than Ninja's solution and with hardware accelerated CSS3 animation. http://jsfiddle.net/pdb4kb1a/2/ Just make sure that the transition time (1s) is the same as the first timeout function (1000(ms)).
Plain JS
var imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').className += "fadeOut";
setTimeout(function() {
document.getElementById('slider').src = imgArray[curIndex];
document.getElementById('slider').className = "";
},1000);
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout(slideShow, imgDuration);
}
slideShow();
CSS
#slider {
opacity:1;
transition: opacity 1s;
}
#slider.fadeOut {
opacity:0;
}
As an alternative. If you are trying to make a slider.
The usual approach is to animate a frame out and animate a frame in.
This is what makes the slide effect, and the fade effect work. Your example fades in. Which is fine, but maybe not what you really want once you see it working.
If what you really want is to animate images in and ...OUT you need something a little more complex.
To animate images in and out you must use an image element for each, then flip one out and flip one in. The images need to be placed on top of each other in the case of a fade, if you want to slide you lay them beside each other.
Your slideshow function then works the magic, but before you can do that you need to add all those images in your array into the dom, this is called dynamic dom injection and it's really cool.
Make sure you check the fiddle for the full working demo and code it's linked at the bottom.
HTML
<div id="slider">
// ...we will dynamically add your images here, we need element for each image
</div>
JS
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();
Fiddle:
http://jsfiddle.net/f8d1js04/2/
you can use this code
var fadeEffect=function(){
return{
init:function(id, flag, target){
this.elem = document.getElementById(id);
clearInterval(this.elem.si);
this.target = target ? target : flag ? 100 : 0;
this.flag = flag || -1;
this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);
},
tween:function(){
if(this.alpha == this.target){
clearInterval(this.elem.si);
}else{
var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
this.elem.style.opacity = value / 100;
this.elem.style.filter = 'alpha(opacity=' + value + ')';
this.alpha = value
}
}
}
}();
this is how to use it
fadeEffect.init('fade', 1, 50) // fade in the "fade" element to 50% transparency
fadeEffect.init('fade', 1) // fade out the "fade" element
Much shorter answer:
HTML:
<div class="js-slideshow">
<img src="[your/image/path]">
<img src="[your/image/path]" class="is-shown">
<img src="[your/image/path]">
</div>
Javascript:
setInterval(function(){
var $container = $('.js-slideshow'),
$currentImage = $container.find('.is-shown'),
currentImageIndex = $currentImage.index() + 1,
imagesLength = $container.find('img').length;
$currentImage.removeClass('is-shown');
$currentImage.next('img').addClass('is-shown');
if ( currentImageIndex == imagesLength ) {
$container.find('img').first().addClass('is-shown');
}
}, 5000)
SCSS
.promo-banner {
height: 300px;
width: 100%;
overflow: hidden;
position: relative;
img {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
z-index: -10;
transition: all 800ms;
&.is-shown {
transition: all 800ms;
opacity: 1;
z-index: 10;
}
}
}
I have the following code which is going to fade some images but I am interested if there is a way to handle this in CSS.
$("#top").stop(true, true).delay(0).fadeTo(fadeTime * 100, 0);
$("#back").stop(true, true).delay(0).fadeTo(fadeTime * 100, 1, function () {
if (curLoop < loops) {
if (curImg < imgNo) {
prevImg = curImg
curImg++
} else {
prevImg = imgNo
curImg = 1;
curLoop++console.log("LOOP");
}
document.getElementById("back").style.opacity = 0;
document.getElementById("top").style.opacity = 1;
document.getElementById("back").src = "frames/frame_" + curImg + ".jpg";
document.getElementById("top").src = "frames/frame_" + prevImg + ".jpg";
} else {
console.log("STOPPED");
window.clearInterval(myVarSTD);
}
if (!initialized) {
myVarSTD = setInterval(function () {
startAnimation()
}, delay * 1000);
initialized = true;
}
});
You can't loop through image sources in a pure CSS animation but the below fade effect is possible with CSS3 animations. Here the front and back images are absolutely positioned and using opacity animation they are faded in and out in an infinite loop. I have used 2 div with background-image but you could do the same for img element also.
Refer inline comments within the snippet for more explanation of the animation's CSS code.
.front,
.back {
position: absolute; /* absolute positioning puts them one on top of other */
height: 200px;
width: 200px;
animation: fade-in-out 10s linear infinite; /* first is animation keyframe's name, second is the duration of the animation, third is timing function and fourth is iteration count */
}
.front {
background-image: url(http://lorempixel.com/200/200/nature/1);
}
.back {
background-image: url(http://lorempixel.com/200/200/nature/2);
z-index: -1; /* keeps the element behind the front */
animation-delay: 5s; /* delay is equal to half the animation duration because the back has to fade-in once the front has faded-out at 50% */
}
#keyframes fade-in-out { /* animation settings */
0%, 100% {
opacity: 1; /* at start and end, the image is visible */
}
50% {
opacity: 0; /* at the mid point of the animation, the image is invisible */
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='front'></div>
<div class='back'></div>
Yes, it is. Your code capture some elements using getElementById as back and top.
You can use the following code to change CSS properties of those elements:
$('#back').css({'opacity':'1'});
Implemented in your code:
$("#top").stop(true, true).delay(0).fadeTo(fadeTime*100, 0);
$("#back").stop(true, true).delay(0).fadeTo(fadeTime*100, 1, function(){
if(curLoop<loops){
if(curImg<imgNo){
prevImg = curImg
curImg++
}else{
prevImg = imgNo
curImg = 1;
curLoop++
console.log("LOOP");
}
$('#back').css({'opacity':'0'});
$('#top').css({'opacity':'1'});
document.getElementById("back").src = "frames/frame_"+curImg+".jpg";
document.getElementById("top").src = "frames/frame_"+prevImg+".jpg";
}else{
console.log("STOPPED");
window.clearInterval(myVarSTD);
}
if(!initialized){
myVarSTD = setInterval(function(){startAnimation()},delay*1000);
initialized = true;
}
});
jQuery Transit is an awesome plugin which mimics jQuery's animation functions but in CSS. You get a much higher framerate using CSS too!
I tried the CSS route but all new to me and learning still but cannot seem to work it out. My JS below switches the background position to show a new image in the sprite every 1 second but wondering if anyone knew how I can kind of give it a small scale effects so when it changes grows a little then back to normal size before change to the next background position?
JS:
// Avatar animations
var avatarInterval;
function startAvatarAnimation() {
var i = 0;
var avatarSpeed = 500;
var avatarCount= 11;
var avatarHeight = 250;
var avatarTotalHeight = 2750;
avatarInterval = setInterval(function(){
i++;
if(i > 11){
i = 0;
}
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' });
$(".avatars").toggleClass('scaleIn', 'scaleOut');
}, avatarSpeed);
return false;
}
function stopAvatarAnimation(){
clearInterval(avatarInterval);
$(".avatars").css({'background-position' : '0 0' });
return false;
}
JS below switches the background position to show a new image in the
sprite every 1 second but wondering if anyone knew how i can kind of
give it a small scale effects so when it changes grows a little then
back to normal size before change to the next background position?
Try utilizing transition at css , setting duration to half of avatarSpeed or half of total duration of background-position effect ; setting transitionend event at .one() to prevent recursive call to transitionend handler , .removeClass() , .addClass() to toggle scale effect defined at css
css
.avatars {
transition: transform 500ms ease-in-out;
width: 100px;
height: 100px;
background-image: url(/path/to/background-image);
}
.avatars.scaleIn {
transform: scale(1.1, 1.1);
}
.avatars.scaleOut {
transform: scale(1.0, 1.0);
}
js
// Avatar animations
var avatarInterval;
function startAvatarAnimation() {
var i = 0;
var avatarSpeed = 500;
var avatarCount= 11;
var avatarHeight = 250;
var avatarTotalHeight = 2750;
avatarInterval = setInterval(function(){
i++;
if(i > 11){
i = 0;
}
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' })
.removeClass("scaleOut").addClass("scaleIn")
.one("transitionend", function() {
$(this).removeClass("scaleIn").addClass("scaleOut");
});
}, avatarSpeed);
return false;
}
$(".avatars").on("click", function() {
$(this).removeClass("scaleOut").addClass("scaleIn")
.one("transitionend", function() {
$(this).removeClass("scaleIn").addClass("scaleOut");
})
})
.avatars {
transition: transform 500ms ease-in-out;
width: 100px;
height: 100px;
background-image: url(http://lorempixel.com/100/100/nature);
}
.avatars.scaleIn {
transform: scale(1.1, 1.1);
}
.avatars.scaleOut {
transform: scale(1.0, 1.0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="avatars"></div>
I have this function
var flakeImage = new Image();
function loadImage(){
flakeImage.onload = drawFlake;
flakeImage.src = "game/snowflake.png";
}
and this one that initialises the image
function initFlake() {
flakex = Math.random()*(WIDTH-140)+70;
flakey = (Math.random()*20)+70;
flakes = Math.random()*40;
}
and this one that updates the image so it will look like it s actually falling
function updateFlake(){
flakey = flakey + 1;
}
and also the draw function
function drawFlake() {
context.drawImage(flakeImage, flakex, flakey, flakes, flakes);
}
I want to make it look like it s snowing in my canvas. I can't use a for loop because it will just modify the same picture . I tried making a big array with the same picture, but in the end I don't get that effect .. because the images have to keep falling randomly . How should I combine an array with that image stored at random positions with an interval to get that effect ?
You can use setInterval().
doSomething: function() {
clearInterval(myInterval);
myInterval = setInterval(function() {
// update flake position
updateFlake();
}, timeInMilliseconds);
},
This runs the function given as a parameter every timeInMilliseconds milliseconds. The setInterval() function returns an ID which you can pass to clearInterval() in order to stop updating.
You can also pass a function directly.
doSomething: function() {
clearInterval(myInterval);
myInterval = setInterval(updateFlake, timeInMilliseconds);
},
EDIT: OP, you can do this just fine without relying on HTML5 canvas, instead use DOM elements:
JS BIN
Javascript:
function update () {
var myInterval = null;
clearInterval(myInterval);
myInterval = setInterval(function() {
// update flake position
$("#holder > img").each(function() {
if ($(this).position().top >= $(window).height())
$(this).remove();
else
$(this).css({top: $(this).position().top+=3});
});
}, 50); //update each of the drawn children
}
function drawFlake() {
clearInterval(myInterval);
var myInterval = null;
myInterval = setInterval(function() {
var randX = (Math.floor((Math.random() * $(window).width()) + 1));
var $img = $('<img>');
$img.attr('src','flake.png');
$("#holder").append($img);
$img.css({left: randX, top: 0, position:'absolute'});
}, 2000); //draw a new flake every 2 seconds
update();
}
HTML:
<body onload="drawFlake()">
<div id="holder"></div>
</body>
CSS:
body {
background: white;
}
#holder {
position: relative;
width: 100%;
height: 100%;
}
I have this loading screen script that I'd like to implement into a project.
However it requires jQuery. And since none of the elements in the page need jQuery, I'd like to save some space and avoid adding it.
Is there any way I can deliver the exact same function with pure JavaScript?
HTML:
<body onload="hide_preloader();">
<div class="preloader"> <div class="loader"></div> </div>
</body>
jQuery:
jQuery(window).load(function() { rotate = 0; $(".preloader").fadeOut(250); });
Thanks
Yes, this is actually surprisingly easy. You can do the fade with CSS transitions instead.
First, let's define some CSS:
.preloader {
transition: opacity 0.25s linear; /* when we change the opacity, use these transition settings */
}
.preloader.fade {
opacity: 0; /* when we add the class fade, set the opacity to 0 using the above transition */
}
Now we simply have to add the fade class with Javascript:
window.onload = function() {
var preloader = document.getElementsByClassName('preloader')[0];
preloader.className += ' fade';
setTimeout(function(){
preloader.style.display = 'none';
}, 300);
};
Browsers that don't understand transition will set opacity to 0 immediately, while as an absolute failsafe (e.g. for browsers that don't understand opacity) we set display to none after a second for everyone.
jsFiddle showing this effect. (Obviously you will style .preloader differently.)
Try something like this:
// taken from http://stackoverflow.com/q/13733912/2332336
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
and this html:
<body onload="fade(document.getElementById('preloader'));">
<div id="preloader"> <div class="loader"></div> </div>
</body>
This should work:
window.onload = function(){
var preloader = document.querySelector('.preloader');
var startTime = new Date().getTime();
function fadeOut(){
var passedTime = new Date().getTime() - startTime;
var opacity = Math.max(250 / (250 - passedTime), 0);
preloader.style.opacity = opacity;
if(opacity){
setTimeout(fadeOut, 0);
}
}
setTimeout(fadeOut, 0);
}