How to give transition effects to dynamically changing image backgrounds using JavaScript - javascript

I have a page wherein the background image for a particular div keeps changing dynamically. I wanna be able to give some transition effects on the images. The page runs on pure javascript. Here's my code:
var bgArray = ["images/1.jpg", "images/2.jpg", "images/3.jpg"];
var i = 0;
function myFunction() {
setInterval(function() {
if (i == 3) {
i = 0;
}
var urlString = bgArray[i];
var x = document.getElementById("myDiv");
x.style.background = "url(" + bgArray[i] + ") no-repeat";
x.style.backgroundSize = "1366px";
i = i + 1;
}, 6000);
}
myFunction();
Thank you.

#myDiv {
transition: background 1s;
}

HTML code
<div id = "myDiv"></div>
CSS code
#myDiv{
width: <yourDivWidth>;
height: <yourDivHeight>;
background-size: cover;
}
Javascript code
var box = document.getElementById("myDiv");
var imagesList = ["url('images/1.jpg')", "url('images/2.jpg')", "url('images/3.jpg')"];
i = 0;
box.style.backgroundImage = imagesList[i];
function nextImg(){
box.style.backgroundImage = imagesList[i+1];
//box.style.width = "1366px";
//box.style.height = "1366px";
//declare your width and height of div in css and give background-size: cover;.
i = i+1;
if(i == imagesList.length){
i = 0;
box.style.backgroundImage = imagesList[i];
}
}
window.onload = setInterval(nextImg, 6000);
Wait for 6 sec and see the background images changing.
If you want to set background image for the first 6sec also, then you can set that in your CSS.
Comment if u have any doubts.

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

Image slider transition not cycling back properly

I attempted to make a image slider that transition to a new image in a few second. However, for some reason it does not go back to the picture in the beginning and seems to try to awkwardly transition. Here the link to the rest of the code https://codepen.io/anon/pen/YvPdNj
var i = 0; //title
var size = 0 //image
var fade = 4000;
function imgTransition() {
var transit = document.getElementsByTagName("img")
for(var i= 0; i < transit.length - 1; i++) {
transit[size].style.opacity = 0;
}
if (size < transit.length - 1) {
size++;
transit[size].style.opacity = 1;
}
else {
size = 0;
transit[size].style.opacity = 1;
}
setInterval('imgTransition()', fade);
}
window.onload = function() {
imgTransition();
};
Here are the few changes I made to your code:
First I made changes to your global variables as I added imgind for image index, transit for the image collection then I assign the transit and size variable in the load event so you don't have to assign them again and again in the code then I Commented the function titleTransition() call in the load event as it is not declared (which you might use later on) and also made the 1st image's opacity to 1 as it is to be displayed first and then called the setInterval(imgTransition, fade); instead of imgTransition() so that the set interval is sepearte of code and is not calling it self.
Here take a look at this modified snippet:
Snippet
var i = 0; //title
var imgind = 0;
var size = 0 //image
var time = 3000;
var fade = 4000;
var transit = null;
function imgTransition() {
transit[imgind].style.opacity = 0; //hiding the indexed image
imgind++; //incrementing the image index
if (imgind >= size) //checking if the index is greater then or equals to size
imgind = 0; //setting index to 1st image i.e 0.
transit[imgind].style.opacity = 1; //displaying the next image
}
window.onload = function() {
transit = document.getElementsByTagName("img"); // get the collection of images
size = transit.length; //get the size of images
transit[imgind].style.opacity = 1; //to set the opacity of 1st image
setInterval(imgTransition, fade);
//titleTransition(); //undefined funciton
};
img {
transition: all .5s ease-in;
left: 160px;
position: absolute;
width: 30%;
height: 50%;
margin: 0;
padding: 0;
opacity: 0;
}
<img src="https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/68dd54ca-60cf-4ef7-898b-26d7cbe48ec7/10-dithering-opt.jpg" alt="Mountain View" width="500" height="377">
<img src="https://i2.wp.com/beebom.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg?resize=640%2C426" alt="Mountain View" width="500" height="377">

How to make vertical auto scrolling image inside div?

I need auto scrolling image placed inside a div. I saw a code for horizontal auto scroll on this page
http://www.dynamicsights.com/cssscrollback.php
I modified it a little to turn it into vertical auto scroll, but for some reason it stopped working. Can someone please tell me what I did wrong, and is there easier way to make vertical auto scroll?
<div id="scroller"></div>
css:
#scroller
{
width:250px; height:120px;
background-image:url(images/background.png); /* size of that image is 250x600 */
}
js:
function StartMove()
{
var BGImage = new Image();
BGImage.src = "images/background.png";
window.cssMaxHeight = 600;
window.cssYPos = 0;
setInterval("MoveBackGround()", 50);
}
function MoveBackGround()
{
window.cssYPos ++;
if (window.cssYPos >= window.cssMaxHeight)
{
clearInterval(MoveBackGround())
}
toMove=document.getElementById("scroller");
toMove.style.backgroundPosition="0 "+window.cssYPos+"px";
}
Code has so many global variables and removing the interval is wrong.
(function() {
var cssMaxHeight, cssYPos, interval, moveTo;
function MoveBackGround() {
cssYPos++;
if (cssYPos >= cssMaxHeight) {
window.clearInterval(interval);
}
toMove = document.getElementById("scroller");
toMove.style.backgroundPosition = "0 " + cssYPos + "px";
}
function StartMove() {
var BGImage = new Image();
BGImage.src = "images/background.png";
cssMaxHeight = 600;
cssYPos = 0;
interval = setInterval(MoveBackGround, 50);
}
StartMove();
}());

Chrome crashes when trying to modify CSS3 animation from Javascript

I have an HTML file with this:
<div id="container"></div>
and I have a stylesheet with a CSS3 animation defined:
.image {
position: absolute;
-webkit-animation-name: image-create;
-webkit-animation-duration: 1s;
}
#-webkit-keyframes image-create {
from {
width: 0px;
height: 0px;
}
to {
width: 500px;
height: 500px;
}
}
This should make an image grow from 0x0 to 500x500.
In my Javascript file I have the following:
var findAnimation = function(name) {
for (var i in document.styleSheets) {
var styleSheet = document.styleSheets[i];
for (var j in styleSheet.cssRules) {
var rule = styleSheet.cssRules[j];
if (rule.type === 7 && rule.name == name) {
return rule;
}
}
}
return null;
}
var addImage = function(x, y, src) {
var image = new Image();
image.src = src;
image.className = "image";
image.style.width = "500px";
image.style.height = "500px";
image.style.left = x;
image.style.top = y;
image.onload = function() {
document.getElementById("container").appendChild(image);
var animation = findAnimation("image-create");
for (var i in animation.cssRules) {
var rule = animation.cssRules[i];
if (rule.keyText == "0%") {
rule.style.top = y;
rule.style.left = x;
}
if (rule.keyText == "100%") {
rule.style.top = 0;
rule.style.left = 0;
}
}
}
}
addImage(100, 100, "http://i.imgur.com/KGfgH.jpg");
​
When addImage() is called, I'm trying to create an image at the coordinates (x, y). The animation should make it grow while also move from the location where the image was created (x, y) to the top left corner (0, 0).
Instead, Chrome just crashes to the "Aw, snap" page. Does anyone know why this is the case?
EDIT: Here is an example. This crashes for me if I visit it: http://jsfiddle.net/LVpWS/10/
In this one I commented out some lines and it does not crash: http://jsfiddle.net/LVpWS/21/
EDIT2: It works if I switch back to Chrome 20.
I've isolated the error:
The page crashes (Aw, snap) when a new property is added to a WebKitCSSKeyframeRule instance.
The bug can be reproduced in Chrome 21.0.1180.57 using the following code: http://jsfiddle.net/LVpWS/68/
<style id="sheet">
#-webkit-keyframes test {
from {}
}</style><script>
var keyFramesRule = document.getElementById('sheet').sheet.cssRules[0];
var keyFrameRule = keyFramesRule[0];
keyFrameRule.style.top = 0;</script>
This crash does not happen when the property already exists in the rule. Replace from {} with from{top:1px;} to check that: http://jsfiddle.net/LVpWS/69/.

webkit transition syntax in javascript?

I'm looking for the webkitTransition object reference here
function spawnAnimation(what){
//sets the moving element
var moveingEl = document.getElementById(what);
//gives temp transition property
moveingEl.style.WebkitTransition = "left 2s";
// moveingEl.style.webkitTransition = "top 500ms";
var cLeft = moveingEl.style.left
var cleft = Number(cLeft.slice(0, -2));
var cTop = moveingEl.style.top
var cTop = Number(cTop.slice(0, -2));
moveingEl.style.left = cLeft+200 + "px";
}
This does not work.I would like to give the element a transition property, then make it move to the right. When this code is called it just immediately moves to the right with no animation. bummer :(. I don't want to predefine it in CSS, I would like to dynamically add it and then remove it.
You can use style.setProperty to modify any property using its CSS name as string, including -moz-* and -webkit-* properties.
const style = document.getElementById('my-div').style
const prop = (k, v) => style.setProperty(k, v)
function bounce() {
prop("-webkit-transition", "top .5s ease-in");
prop("top", "50px");
setTimeout(() => {
prop("-webkit-transition", "top .75s cubic-bezier(0.390, 0.575, 0.565, 1.000)");
prop("top", "0px");
}, .5 * 1000)
}
prop("-webkit-transition", "top .5s ease-in");
setInterval(bounce, (.75 + .5) * 1000);
#my-div {
background: red;
border-radius: 50%;
width:50px;
height:50px;
position:absolute;
top: 0px;
}
<div id="my-div"></div>
Allow 1ms for the rendered to get the thread back.
setTimeout(function() {
myElement.style.height = '200px'; /* or whatever css changes you want to do */
}, 1);​
You can use:
element.style.webkitTransition = "set your transition up here"
I know it's a workaround, but can you use jQuery?
$(moveingEl).css('-webkit-transform', 'translateX(200px)');
<script>
$(document).ready(function(){
var x = 100;
var y = 0;
setInterval(function(){
x += 1;
y += 1;
var element = document.getElementById('cube');
element.style.webkitTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome
element.style.MozTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
},50);
//for other browsers use: "msTransform", "OTransform", "transform"
});
</script>

Categories