Fade my background change - javascript

I have to change a div bg each 5 seconds.
But I really want to make this transition as a fade effect..
I'm doing this (but I get an abrupt transition instead of a fade one...):
<script>
var bgArr = ["images/1.jpg", "images/2.jpg", "images/3.jpg" ];
var i=0;
var interval = self.setInterval("changeBg()", 5000)
function changeBg() {
if (i>(bgArr.length-1) ) {
i=0
$("#header").css("background-image", "url("+bgArr[i]+")");
}
else {
$("#header").css("background-image", "url("+bgArr[i]+")");
}
i++;
};
</script>
How can I do this transition as a fade... without showing a white space (I mean.. The second image appears slowly over the first one)??
I'm really stuck.. :(

You can try the bgshuffle script. It uses JqueryUI. You will have to include JqueryUI somewhere in your page. The script is posted on github, feel free to extend it if you like:
https://github.com/vikaskumarsingh123/bgshuffle/
You can simply call it like:
shuffleBG( ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'] );//the array of wallpapers
or Advanced Usage:
shuffleBG(['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'], //the array of wallpapers
'10000', //time between wallpaper change, defaults to 10000ms (10secs)
'1000', //fade in fade out animation speed, defaults to 1000ms
'white' //color to fade in and out of, defaults to body backgroundColor or white
);
You will usually be calling this function on document.load and it will start changing the background image fade-in-out every 10 seconds.

How about using .fadeTo():
DEMO: https://jsfiddle.net/w13bhcgt/
$(function () {
var bgArr = ['http://png-5.findicons.com/files/icons/1243/hello_kitty/256/flower.png',
'http://www.vectorimages.org/01/01201101251549265911.png',
'http://media.janm.org/exhibitions/hellokitty/JANM-HelloKitty-icon-bow.png'];
var i = 0;
function Change() {
$("#header")
.fadeTo('slow', 1)
.css("background-image", "url(" + bgArr[i] + ")")
.fadeTo('slow', 0);
i++;
if (i < bgArr.length) setTimeout(Change, 2000);
}
Change(0);
});

Related

Fade to Slide Javascript

I got this website, www.harispapadakis.eu and I'm using this code
function changeBackground() {
++currentBackground > 2 && (currentBackground = 0),
$(".c-hero").fadeOut(4e3, function() {
$(".c-hero").css({
"background-image": "url('" + backgrounds[currentBackground] + "')"
}),
$(".c-hero").fadeIn(3e3)
}),
setTimeout(changeBackground, 15e3)
}
var currentBackground = 0,
backgrounds = [];
backgrounds[0] = "media/main.jpg",
backgrounds[1] = "media/main2.jpg",
backgrounds[2] = "media/main3.jpg",
$(document).ready(function() {
setTimeout(changeBackground, 7500)
});
(edit note: formatted from minified code, in which if is minified to &&, ; is minified to , and 3000 is minified to 3e3)
This code, is changing with FadeIn and FadeOut the background src...
I want to change the fade with slide to left... It's changing the background picture and I want a nice animation..
Thanks in advance
This answer may help: How do you fadeIn and animate at the same time?
Rather than using .fadeIn, consider using jQuery's .animate function to perform multiple css transitions.
For example, instead of:
$(".c-hero").fadeIn(3e3)
Try doing #see http://api.jquery.com/animate/:
$(".c-hero").animate(
{opacity: 1, left: "-=50"}, // css attributes to animate
3000, // duration in seconds
function(){ /**callback function after it completes**/}
});

jQuery background image change on timer

I have a div:
<div class="coverImage" style="background-image:url('3.2.5\\assets\\img\\backgroundCanvas1.jpg');"></div>
and an attached jQuery script to rotate its background every 20 seconds
var coverChange =
{
init: function()
{
var itemInterval = 20000;
var numberOfItems = 4;
var currentItem = 1;
$('.coverImage').attr("style", "background-image:url('3.2.5/assets/img/backgroundCanvas"+currentItem+".jpg'");
//loop through the items
var infiniteLoop = setInterval(function(){
$('.coverImage').attr("style", "background-image:url()");
if(currentItem == numberOfItems -1){
currentItem = 1;
}else{
currentItem++;
}
$('.coverImage').attr("style", "background-image:url('3.2.5/assets/img/backgroundCanvas"+currentItem+".jpg'");
}, itemInterval);
}
};
coverChange.init();
When the image changes it happens to white out the bottom half until I scroll slightly. My main ask is help with a fadeIn of the new image. (everything else is secondary)
I have experimented using the jQuery fadeIn property but cannot get it to work in a seamless aesthetically pleasing way.
I am not looking for code elegance only function, as you can tell :-)
P.S Loading the image initially via CSS did not work.
You should be able to add a simple CSS transition to your coverImage element.
.coverImage {
transition: background 1s;
}
I've created a working example at https://jsfiddle.net/mark_c/pa44n42k/1/
For a fade in out effect, you should simply fade out the div before this step:
$('.coverImage').attr("style", "background-image:url()");
and fade it in after this step:
$('.coverImage').attr("style", "background-image:url('3.2.5/assets/img/backgroundCanvas"+currentItem+".jpg'");
For fade in out you can use simple jquery as I suppose you already have but not the right way, so good luck.
This will give you a nice fade in/out effect. :)

Javascript fade in/out effect freezes when hovering quickly over images

I'm playing around with pure JavaScript, so I created a small fade in/out object, to adjust images opacity onmouseover and onmouseout. Fading works fine when the mouseover and mouseout actions are precise:
Start moving the cursor from the white background
Hover over an image
Hover back over the white background
The problem is, as soon as I start to move the mouse "naturally" from one image to another, the fading (or rather the script itself) freezes.
I'm not sure whether it's a animation-speed problem, or there's something I'm missing in the implementation.
If someone has the time to take a look, I would appreciate a peer check, so I can crack the issue and learn new stuff.
Here's a fiddle: http://jsfiddle.net/6bd3xepe/
Thanks!
As I see it, you have one INTERVAL for you FADER, you need one for each IMG.
My jsfiddle fixes this. I added an ALT-attribute to each IMG with "dome" content, so as to circumvent the jsfiddle working on non-cat-images .. ignore that part - commented out below.
There are some fundamental things wrong with the design - keeping track of objects & references is key. Usage of "this" & "that" aren't helping in the current implementation (see comments to OP). Also, on another note, the usage of "toFixed(2)" is not really required IMHO and you can shorten "o = o + 0.1" to "o += 0.1".
JS:
var fader = {
target: document.getElementsByTagName('img'),
interval: [],
speed: 25,
default_opacity: 1,
init: function() {
this.bindEvents();
},
// Get element's opacity and increase it up to 1
fadeIn: function(element) {
var element_opacity = this.getOpacity(element),
that = this,
idx = element.getAttribute('data-idx');
console.log("fI: "+idx+" "+element_opacity);
this.default_opacity = element_opacity.toFixed(2);
this.interval[idx] = setInterval(function() {
if (element_opacity.toFixed(2) < 1) {
element_opacity = element_opacity + 0.1;
element.style.opacity = element_opacity.toFixed(2);
} else {
clearInterval(that.interval[idx]);
}
}, that.speed);
},
// Get current opacity and decrease it back to the default one
fadeOut: function(element) {
var element_opacity = this.getOpacity(element),
that = this,
idx = element.getAttribute('data-idx');
console.log("fO: "+idx+" "+element_opacity);
this.interval[idx] = setInterval(function() {
if (element_opacity.toFixed(2) > that.default_opacity) {
element_opacity = element_opacity - 0.1;
element.style.opacity = element_opacity.toFixed(2);
} else {
clearInterval(that.interval[idx]);
element.removeAttribute('style');
}
}, that.speed);
},
// Get opacity of an element using computed styles
getOpacity: function(element) {
var styles = window.getComputedStyle(element),
opacity = parseFloat(styles.getPropertyValue('opacity'));
return opacity;
},
bindEvents: function() {
var that = this, count = 0;
for (var i in this.target) {
// the whole "dome" is just a fsfiddle hack - otherwise it sees 7 images instead of 4!
//if( this.target[i].alt == "dome" ){
console.log("COUNT: "+count);
this.target[i].setAttribute('data-idx',count);
this.target[i].onmouseover = function() {
that.fadeIn(this);
}
this.target[i].onmouseout = function() {
that.fadeOut(this);
}
count++;
//}
}
}
};
fader.init();

jQuery .Animate Opacity and .FadeOut/In Both Not Working Inside SetInterval

I trying to make what appears to the user to be an image fader. A string of images fade into each other. All the solutions that I found were complex, and normally required an for every image. I've come up with what should be a simple solution. It's working 90% on Firefox/Chrome/IE11 on Windows. On Android Chrome it's having issues.
Basically my idea is, I have two divs, absolutely positioned, one on top of the other. Both start with a background, sized to cover. The top one fades out, revealing the bottom one, and at the end of the animation, the background-image of the top one (current hidden) is changed to image 3. After a pause, it fades back in, and the background-image of the bottom one is changed to image 4. This repeats indefinitely.
HTML:
<div class="slideshow" id="slideshow-top"></div>
<div class="slideshow" id="slideshow-bottom"></div>
CSS:
.slideshow {
display:block;
background-size:cover;
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
}
#slideshow-top {
z-index:-5;
background-image:url(http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg);
}
#slideshow-bottom {
z-index:-10;
background-image:url(http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg);
}
Javascript:
var url_array = [
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-3.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-4.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-5.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-6.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-7.jpg',
'http://www.walldoze.com/images/full/2013/12/04/wallpapers-desktop-winter-nature-x-wallpaper-backgrounds-natureabstract-designs-interesting-hd-19045.jpg'
];
var count = 1;
setInterval(function() {
if (count%2) { // Fade In
jQuery('#slideshow-top').animate({opacity:0}, '200000', function() {
jQuery('#slideshow-top').css('background-image','url('+url_array[count]+')');
});
}
else { //Fade Out
jQuery('#slideshow-top').animate({opacity:1}, '200', function() {
jQuery('#slideshow-bottom').css('background-image','url('+url_array[count]+')');
});
}
count = (count == url_array.length-1 ? 0 : count + 1);
}, 2000);
http://jsfiddle.net/5eXy9/
As seen in the Fiddle above, this mostly works. However, it seems to ignore the length of the animation. Using .fadeOut has the same effect. I've tried going from 200 to 20000, and there doesn't seem to be a difference.
I'm not sure if this is tied into the other issue, which is that on Android (Galaxy S4, Chrome, Android 4.x), the animation doesn't occur at all. It simply changes images. Any ideas?
EDIT: Jan 10 - Timing problem is fixed, but the main issue (Android) is still unsolved. Any thoughts?
The interval keeps going, so when increasing the animation speed, you have increase the interval speed as well.
The way you've built this, you should always keep the speed of both animations equal to the interval, or if you need a delay, increase the interval compared to the animations so it at least has a higher number than the highest number used in the animations.
The reason changing the speed doesn't work at all for you, is because it should be integers, not strings, so you have to do
jQuery('#slideshow-top').animate({opacity:0}, 200000, function() {...
// ^^ no quotes
I would do something like this
var url_array = [
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-1.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-2.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-3.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-4.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-5.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-6.jpg',
'http://www.andymercer.net/wp-content/uploads/2013/12/slider-7.jpg',
'http://www.walldoze.com/images/full/2013/12/04/wallpapers-desktop-winter-nature-x-wallpaper-backgrounds-natureabstract-designs-interesting-hd-19045.jpg'];
var count = 1;
var speed = 2000,
delay = 1000;
$.each(url_array, function(source) { // preload
var img = new Image();
img.src = source;
});
setInterval(function () {
if (count % 2) { // Fade In
jQuery('#slideshow-top').animate({
opacity: 0
}, speed, function () {
jQuery('#slideshow-top').css('background-image', 'url(' + url_array[count] + ')');
});
} else { //Fade Out
jQuery('#slideshow-top').animate({
opacity: 1
}, speed, function () {
jQuery('#slideshow-bottom').css('background-image', 'url(' + url_array[count] + ')');
});
}
count = (count == url_array.length - 1 ? 0 : count + 1);
}, speed + delay);
FIDDLE

Equivalent of #keyframes for jQuery

I'm looking for a way to emulate the CSS #keyframes animations using jQuery.
I need to change the background image each x seconds following a list of images provided when the user moves mouse over an element.
The CSS animations should be:
.readon:hover {
animation: readonin 2s;
}
#keyframes readonin {
0% { background-image: url(1.png); }
50% { background-image: url(2.png); }
100% { background-image: url(3.png); }
}
I've found plugins like Spritely but they works with sprites and I need instead to change the image background of the element.
Use the set-interval function of Javascript seems a bad solution because I can't find a way to stop the animation when the user moves the mouse out of the element.
Use something like...
var images = ["1.png", "2.png", "3.png"];
var $element = $(".readon");
var interval = null;
$element.hover(function () {
var $this = $(this);
var i = 0;
var fn = function () {
$this.css("background-image", "url(" + images[i] + ")");
i = ++i % images.length;
};
interval = setInterval(fn, 666);
fn();
},
function () {
clearInterval(interval);
$(this).css("background-image", "none");
});
jsFiddle of a similar concept (with background colours).
It should be clear enough to see what's going on. Basically we start looping over the images and setting them as the background image on mouse over, and reset it when the mouse leaves.
You can use a library like jQuery-Keyframes
to generate new keyframes at runtime if that is what you are after.

Categories