Javascript image rotator flickers occasionally - javascript

I've created a JS/CSS image rotator that rotates 5 different images on a section of my website, with a fade in/out effect in CSS.
On desktop/laptop, the images rotate perfectly smoothly, although roughly once every loop, the images flicker and jump quickly to the next one. What is the cause of this?
Source:-
CSS
#keyframes fadeinout {
0%, 100% { opacity: 0; }
50% { opacity: 1; }
}
#rotator {
animation: fadeinout 3s;
}
JS
function clientRotator(){
var section = document.getElementById("clients");
var clientImg = document.createElement("img");
clientImg.setAttribute("id", "rotator");
section.appendChild(clientImg);
clientImg.src = "assets/exxon-mobil.png";
var imgArray = ["assets/shell.png", "assets/bp.png", "assets/talisman.png", "assets/cnr-international.png", "assets/exxon-mobil.png"];
var delaySeconds = 3;
var iteration = 0;
setInterval(function(){
section.removeChild(clientImg);
clientImg = document.createElement("img");
clientImg.setAttribute("id", "rotator");
section.appendChild(clientImg);
clientImg.src = imgArray[iteration];
clientImg.setAttribute("alt", "Oil & Gas - Gas Turbine Overhauls");
if (iteration < imgArray.length-1){
iteration += 1;
}
else {
iteration = 0;
}
}, delaySeconds * 1000)
}

The flicker is caused by small desync of the js and css, you can cause the flicker (for testing) by reducing the css animation from 3s to 2s.
To fix it just add to the #rotator the property opacity: 0;.

Related

Adding a fade between JavaScript slideshow? [duplicate]

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;
}
}
}

Include a fadeIn(Slow) on this changeable background Image javascript

I have a Javascript code to change the background image randomly and works fine, but is very rough. I would like to make some kind of transition between images, I would like to use fadeIn(slow) but don't know how to incorporate it to my code, can someone help me? Cheers!
JAVASCRIPT
window.onload = function () {
// Array of Images
var backgroundImg=["https://image1.com",
"https://image2.com",
"https://image3.com",
"https://image4.com"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.getElementById("sectionAbout").style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
Easy solution is to pass the transition handling to your browser, and all you should care about is the background changing.
Say we want to animate the body background.
Here's working example with colors, but can be done with images as well just use backgroundImage insead of backgroundColor
var arr = ['blue', 'red', 'pink', 'yellow', 'brown']
var i = 0;
document.getElementById('l').addEventListener('click', function() {
document.body.style.backgroundColor = arr[i];
i++
if (i == arr.length)
i = 0;
});
body {
transition: background ease 2s;
}
<button id="l">OK</button>
EDIT : In case of Images, You would want to avoid, the jerky animations caused by the images not being loaded.
var arr = ["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g", "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"];
var i = 1;
var img = new Image();
img.onload = function() {
document.body.style.backgroundImage = 'url(' + img.src + ')';
i++;
if (i == arr.length)
i = 0;
setTimeout(function() {
img.src = arr[i];
}, 5000);
};
img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA";
body {
transition: background ease 2s;
}
Try to use https://greensock.com/gsap, it is really efficient in transitions and animation handling. Many experts use it for efficient transition or animation management.
When you change the backgroundImage via javascript the image is loaded the moment the script is executed, so there will be a noticable lag. A solution is to load the images in css or to preload via js.
In below solution I added the images via css so there is no lag. Because Firefox doesn't support transition of background-image the script z-indexes the images in the right order and fades them (with a css animation on opacity).
html:
<div id="sectionAbout">
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
</div>
css:
#sectionAbout {
height: 100vh;
}
.img {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-size: cover;
}
.fadeIn {
animation: fadeIn 2s;
}
#keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.img:nth-of-type(1) {
z-index: 1;
background-image: url(http://picsum.photos/400/300?image=1);
}
etc..
js:
var imgDivs = document.querySelectorAll(".img");
setInterval(changeImage, 2000);
var i = 0;
function changeImage() {
i++;
el = imgDivs[i%4];
el.classList.remove("fadeIn");
// force css animation restart
// (https://css-tricks.com/restart-css-animation/)
void el.offsetWidth;
el.style.zIndex = i;
el.classList.add("fadeIn");
}
For a working example see here:
https://jsfiddle.net/tfc0kyp3/3/

Does hiding a div stop animations (CSS or JS)?

Considering any CSS based loader animation as a reference. Typically, when some callback function is executed on success, the div is hidden so as to indicate that the results have arrived. My question is, does hiding the div actually stop the animation? Or do those still continue to use up CPU cycles?
What about non-CSS animations?
TL;DR
My question is, does hiding the div actually stop the animation? Or do those still continue to use up CPU cycles?
Not sure how the animation state is defined internally, but it's not using CPU cycles once hidden.
What about non-CSS animations?
CPU cycles are not used for rendering, but they are used for the JavaScript calculations under the hood.
Detailed answers with relevant examples/tests below:
CSS
As you can see here, the browser (at least in which I tested it) seems not to waste any cycles on invisible elements. It could vary with browsers as well as the browser versions. I assume older browsers don't care about this, but all the modern ones will try to save as much CPU as possible.
Here's a snippet/proof, try doubling the dark divs until it starts choking, then toggle them and see how the light div behaves:
function dbl(){
var c = document.querySelectorAll('div.reg').length;
for(var i = 0; i < c; i++){
var div = document.createElement('div');
div.className = 'reg';
document.body.appendChild(div);
}
}
function toggle(){
var divs = document.querySelectorAll('div.reg');
for(var i = 0; i < divs.length; i++){
divs[i].style.display =
divs[i].style.display == 'none' ?
'inline-block' : 'none';
}
}
div {height: 50px; width: 50px; margin: 2px; display: inline-block; background: #eee; animation: rot 1s linear infinite}
div.reg {background: #ccc}
#keyframes rot {
0% { transform: rotateZ(0deg) }
100% { transform: rotateZ(360deg) }
}
<button onclick="dbl()">Double dark divs</button>
<button onclick="toggle()">Toggle dark divs</button><br>
<div></div>
<div class="reg"></div>
JS (non-CSS)
For the non-CSS stuff, the browser won't waste any cycles on rendering the animations, but the JavaScript animation calculations will most definitely take place.
var r = 1;
var fps = document.querySelector('span');
var lastFrame = new Date();
function dbl(){
var c = document.querySelectorAll('div.reg').length;
for(var i = 0; i < c; i++){
var div = document.createElement('div');
div.className = 'reg';
document.body.appendChild(div);
}
}
function toggle(){
var divs = document.querySelectorAll('div.reg');
for(var i = 0; i < divs.length; i++){
divs[i].style.display =
divs[i].style.display == 'none' ?
'inline-block' : 'none';
}
}
function rot(){
var divs = document.querySelectorAll('div');
for(var i = 0; i < divs.length; i++){
divs[i].style.transform = 'rotateZ(' + r + 'deg)';
}
r = (r+1)%360;
fps.textContent = parseInt(1000 / (new Date() - lastFrame), 10);
lastFrame = new Date();
window.requestAnimationFrame(rot);
}
function kill() {
var divs = document.querySelectorAll('div.reg');
for(var i = 1; i < divs.length; i++){
divs[i].parentElement.removeChild(divs[i]);
}
}
rot()
div {height: 50px; width: 50px; margin: 2px; display: inline-block; background: #eee;}
div.reg {background: #ccc}
<button onclick="dbl()">Double dark divs</button>
<button onclick="toggle()">Toggle dark divs</button>
<button onclick="kill()">Kill dark dupes</button>FPS: <span></span>
<br>
<div></div><div class="reg"></div>
The JS calculations here are very heavy (on purpose) and you can see they keep running in the background.

How to convert a jQuery fade effect in CSS?

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!

Array slide show not working smoothly with javascript

Written some javascript (very new to this) to center the div and make it full screen adjusting as the window does, that works fine but now I have added some script I found online to transition from one image to another using an array. They seem to be contradicting each other messing up the animation, the biggest problem is when I resize the window. Here is my jsfiddle so you can see for yourself. Thanks in advance.
http://jsfiddle.net/xPZ3W/
function getWidth() {
var w = window.innerWidth;
x = document.getElementById("wrapper");
x.style.transition = "0s linear 0s";
x.style.width= w +"px";
}
function moveHorizontal() {
var w = window.innerWidth;
x = document.getElementById("wss");
x.style.transition = "0s linear 0s";
x.style.left= w / 2 -720 +"px" ;
}
function moveVertical() {
var h = window.innerHeight;
x = document.getElementById("wss");
x.style.transition = "0s linear 0s";
x.style.top= h / 2 -450 +"px" ;
}
var i = 0;
var wss_array = ['http://cdn.shopify.com/s/files/1/0259/8515/t/14/assets/slideshow_3.jpg? 48482','http://cdn.shopify.com/s/files/1/0259/8515/t/14/assets/slideshow_5.jpg?48482'];
var wss_elem;
function wssNext(){
i++;
wss_elem.style.opacity = 0;
if(i > (wss_array.length - 1)){
i = 0;
}
setTimeout('wssSlide()',1000);
}
function wssSlide(){
wss_elem = document.getElementById("wss")
wss_elem.innerHTML = '<img src="'+wss_array[i]+'">';
wss.style.transition = "0.5s linear 0s";
wss_elem.style.opacity = 1;
setTimeout('wssNext()',3000);
}
So I whipped up this JSFiddle from scratch, and I hope it helps out. Pure CSS transitions from class to class using your array URLs to switch among the pictures.
Basically this just advances the "active" class to the next one everytime it's called, provided the first picture is set to "active" class.
var pics = document.getElementById('slideshow').children,
active = 0;
function slideshow() {
for (var i = 0; i < pics.length; i++) {
if (i == active && pics[i].className == "active") {
console.log(i, active, (active + 1) % pics.length);
active = (active + 1) % pics.length;
}
pics[i].className = "";
}
pics[active].className = "active";
setTimeout(slideshow, 2000);
}
setTimeout(slideshow, 2000);
And here's the CSS, which absolutely positions the container, and hides all its children unless it has the active class, to which it will transition smoothly.
#slideshow {
position: absolute;
top: 20%;
bottom: 20%;
left: 20%;
right: 20%;
}
#slideshow img {
position: absolute;
max-height: 100%;
max-width: 100%;
opacity: 0;
transition: opacity 1s linear;
}
#slideshow .active {
opacity: 1;
}

Categories