Making background fade in using Javascript - javascript

Hello below is my JS code for a changing background image every 30 seconds. I have this example code too from research, can somebody please please please show me how to integrate the example code into my JS, so the changing image fades in as I simply have no clue where to start and feel completely lost.
My JS
<script>
bgArr = ['images/bg1.jpg', 'images/bg2.jpg', 'images/bg3.jpg'];
bgCur = 0;
backgroundSwitch = function()
{
if (bgCur == bgArr.length) bgCur = 0;
document.body.style.backgroundImage = 'url('+ bgArr[bgCur++]+ ')';
}
window.setInterval(backgroundSwitch, 30000); // Switch every 30 seconds.
</script>
Example JS that I want to integrate
var img = document.getElementById("fade");
var fadeLength = 5500;
var opacity = 0;
var startTime = Date.now();
requestAnimationFrame(function me() {
// It's faded in, stop animating!
if (opacity >= 1) {
return;
}
opacity = (Date.now() - startTime) / fadeLength;
img.textContent = opacity;
img.style.opacity = opacity;
requestAnimationFrame(me);
});
Also is there a way to fit the background to the browser window within the javascript without using css?
Thank you and somebody please help!

One solution here is to use CSS transitions. No JS transition needed.
transition: background-image 6s;
Example

Related

How to evenly time fading transitions?

so I'm trying to create a simple slide show from scratch, and so far I was able to get full screen images to fade out and fade in infinetly, but for some odd reason using setInterval(function(){fade(var)}, 3500);didn't work, maybe someone can explain why the first and last images took way longer than 3,5 seconds to fade. Meanwhile, I was trying to solve that problem by implementing a callback function in the fade(). My example has four images, and they start fading out until it reaches image one, then don't fade out image one and start fading back in image two until image 4, and do this forever, here is my recent attempt to implement a callback function:
var i = 4;
$(document).ready(function(){
fade(i, fade);
});
var fadeIN = false;
function fade(objectID, callbackfn){
var fadeTime = 3500;
if(!fadeIN){
$("#slide-"+objectID).fadeOut(fadeTime);
i--;
if(i === 1) {
fadeIN = true;
}
}
else{
i++;
$("#slide-"+objectID).fadeIn(fadeTime);
if(i === 4){
fadeIN = false;
}
}
if(arguments[1]){
callbackfn(i);
}
}
But that is not working, it fades out image 4, image 3 and stops on image 2. Maybe there is a way to evenly time the fading transitions using the setIntervel(), if so can someone tell me how? Appreciate any help.
Here is a JSFiddle to the code: http://jsfiddle.net/8kgc0chq/ it is not working tho.
Here is the doc for .fadeOut()
There is an optional argument complete:
A function to call once the animation is complete.
Put the next animation in there, they too take a complete (callback) function.
$("#id").fadeOut(fadeTime, function() {
// code to execute after animation complete
});
You need to do it properly with javascript. Easy way fails after last element.
So here is my solution. Can it be improved further, I think yes.. But it does work now. And is future proof to some extent.
I cleaned up css and changed html structure a little.
Demo: http://jsfiddle.net/8kgc0chq/3/
$(document).ready(function () {
$(window).resize(function () {
realTimeHeight();
});
realTimeHeight();
startSlides();
});
function startSlides() {
var fadeTime = 1000,
delay = 1300,
i = 0,
slides = $("#hero-slider > .slide"),
len = slides.length;
slides.hide();
var pF = $('<div class="slide">'), pB = pF.clone();
pF.attr('id', slides.eq(i).attr('id'));
$('#hero-slider').prepend(pF).prepend(pB);
setInterval(fadeThisIn, fadeTime + delay);
function fadeThisIn() {
pB.attr('id', pF.attr('id'));
i = ++i % len;
pF.hide().attr('id', slides.eq(i).attr('id')).fadeIn(fadeTime);
}
}
function realTimeHeight() {
var altura = $(window).height();
$("#hero-slider").css("height", altura);
}

css background-image changing with animation

I tried to change my background image with the following code
$('#mask').css({'background-image' : 'url('changingVar')',
'background-repeat' : 'no-repeat',
'background-position': 'center',
'background-size': 'cover',
});
and having a setTimeout for the waiting time.
However I want a changing animation kinda like : http://www.luckywok.at
The problem is when I use fadeout and fadeIn it's fading out and in my complete screen, since I have a wrapper DIV (#Mask) around everything.
Does anyone have an idea what methods were used on that particular site?
Simple solution.
Fullscreen : http://jsfiddle.net/9GwNG/3/show/
jsfiddle : http://jsfiddle.net/9GwNG/3/
// code was written in a hurry
//
var step = 1;
function bg(){
var opacity = 0.0;
if (step == 3){
n = 3;
step = 1;
opacity = 1.0;
$("#item_"+step).animate({'opacity':opacity},2000);
$("#item_"+n).animate({'opacity': 0.0},2000);
return;
}
n = step+1;
$("#item_"+step).animate({'opacity':opacity},2000);
$("#item_"+n).animate({'opacity':1.0},2000);
step = n;
}
function loop(){
setInterval(bg,4000);
}
setTimeout(loop,500);
Just use CSS- Transitions and a setInterval function.
http://jsbin.com/ugERaZO/1/edit
Transitions are support for > ie9 see caniuse.

Decrease image size automatically over a certain amount of time

I am looking for a script but I'm not sure what to look for.
I have a webpage that has the body tag with a background image.
body {
background: url(eye.gif)repeat;
background-size:91px 91px;
}
What I am hoping to achieve is when the page loads it shows the background image as 991px then slowly decrease by 10px over a set time until the original size of 91px.
I'm not sure if there is away to do this, or even another way that when the page is loaded it is zoomed in and then zooms out automatically over time.
Basically when the page is loaded you will see the image twice and then over time you will see more and more.
Can anyone point me in the right direction.
if you use background-size your using css3 and so you can use keyframes
no javascript needed.
#-webkit-keyframes bganimation{
0%{background-size:991px 991px;}
100%{background-size:91px 91px;}
}
body{
background: url(eye.gif)repeat;
background-size:91px 91px;
-webkit-animation:bganimation 20s linear; // 20s = 20 seconds
}
for more support you need to add the other specific prefixes (-moz,-ms..)
Here is a sample using JQuery:
http://jsfiddle.net/frUvf/16/
$(document).ready(function(){
$('body').animate({'background-size':'10000px'}, 50000);
})
Using vanilla JS:
var lowerBound = 250,
step = 10,
duration = 1000,
image = document.getElementById('image');
(function resizer () {
if (image.clientWidth > lowerBound) {
image.style.width = image.clientWidth - step + 'px';
var timer = setTimeout(resizer, duration);
} else {
clearTimeout(timer);
}
}());
Just change the lowerBound/step/duration variables to whatever you need them to be.
Fiddle
with jquery:
var body = $('body');
var zoom = 2;
var interval_zoom = 0.5;
var time_interval = 90000;
setInterval(function(){
body.css("zoom", zoom);
zoom = zoom - interval_zoom;
if(zoom<=1)
clearTimeout(this);
}, time_interval )
Zoom and interval must be calculated
You could use Javascript for the animation or could take a look at CSS3 Transformations: http://web.archive.org/web/20180414114433/http://www.pepe-juergens.de/2013/02/css3-transform/

Showing/hiding <div> using javascript

For example I have a function called showcontainer. When I click on a button activating it, I want a certain div element, in this case <div id="container">, to fade in. And when I click it again, fade out.
How do I achieve this?
Note: I am not accustomed with jQuery.
So you got a bunch of jQuery answers. That's fine, I tend to use jQuery for this kind of stuff too. But doing that in plain JavaScript is not hard, it's just a lot more verbose:
var container = document.getElementById('container');
var btn = document.getElementById('showcontainer');
btn.onclick = function() {
// Fade out
if(container.style.display != 'none') {
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity -= 5;
container.style.opacity = opacity/100;
if(opacity <= 0) {
clearInterval(fade);
container.style.opacity = 0;
container.style.display = 'none';
}
}, 50);
// Fade in
} else {
container.style.display = 'block';
container.style.opacity = 0;
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity += 5;
container.style.opacity = opacity/100;
if(opacity >= 100) {
clearInterval(fade);
container.style.opacity = 1;
}
}, 50);
}
};
Check the working demo.
Provided you're not opposed to using jQuery per se, you can achieve this easily:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showcontainer').click(function() {
$('#container').fadeToggle();
});
});
</script>
...
<div id="container">
...
</div>
...
<input type="button" id="showcontainer" value="Show/hide"/>
...
Note the missing http: in the beginning of the source of jQuery. With this trick the browser will automatically use http: or https: based on whether the original page is secure.
The piece of code after including jQuery assigns the handler to the button.
Best thing you could do is start now and get accustomed to jQuery.
The page http://api.jquery.com/fadeIn/ has all the example code that could be written here. Basically you want to have the call to fadeIn in your showcontainer function.
function showcontainer() {
$('#container').fadeIn();
}
You can have a look at jQuery UI Toggle.
The documentation turns the use of the library very simple, and they have many code examples.
You'd be as well off learning jQuery as it makes it a lot easier to do things!
From the sounds of it, you could have the container div already in the HTML but with a style of "display:none;", and then simply show it in your click event using (jQuery):
$('#container').fadeIn('slow', function() {
//Any additional logic after it's visible can go here
});

javascript change image slowly with fade using timer and opacity

i am looking for some help with this script i have been working on. here is my file fade.js
the problem is with the changing, it is messed up. please help me find the problem and solution for this, thanks.
JS-file
//image fade script
var opacity = 0;
function changeimg(currentimage){
rnumb = Math.floor(Math.random()*2);
var newimage = "./images/" + rnumb + ".jpg";
if (newimage !== currentimage)
{
document.getElementById("fadeImg").src= newimage;
}
}
function fadein()
{
var fadeImg = document.getElementById('fadeImg');
var browserName=navigator.appName;
if(browserName=="Microsoft Internet Explorer")
{
browserOpacity = opacity / 10;
fadeImg.filters.alpha.opacity = browserOpacity;
}
else
{
browserOpacity = opacity / 1000;
fadeImg.style.opacity = browserOpacity;
}
if(opacity < 1000)
{
initiate();
}
else if(opacity == 1000)
{
changeimg(document.getElementById("fadeImg").src);
opacity = 0;
}
}
function initiate()
{
opacity++;
setInterval("fadein()", 500);
}
index.html
<script type="text/javascript" src="fade.js"></script>
<body onload="initiate()">
<img id="fadeImg" src="images/1.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
JS-fiddle
Here is a Fiddle of the code as well: http://jsfiddle.net/epqKr/2/ (Notice that the code, as it is in the fiddle, may make your browser freeze after a while.
I think you should use a cross-browser library to accomplish things like this.
Microsoft Internet Explorer, especially in versions < 9, is most likely to not behave
as you would expect it does, particularly when you try to use functions which makes use of opacity, alpha-filter and timing. You could try to use jQuery, or Prototype, or MooTools and such frameworks. They all make what you're looking for in simple, secure, better way.
Don't call initiate() from within the fadeIn() function, instead just increment your opacity control variable (i.e, opacity += 1;).
You will probably want to save your setInterval return value to kill the callbacks when you have finished your animation.
You also probably will want to increase the animation speed by lowering the interval.
animId = setInterval("fadeIn()", 5);
i am working on this still, heres what i have now: it doesnt work whatsoever but it looks better.
html
<html>
<head>
<script type="text/javascript" src="fade1.js"></script>
</head>
<body onload="fadetimer()">
<img id="fadeImg" src="1.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
</body>
</html>
script
//image fade script
var opacity = 0;
function changeimg(currentimage){
rnumb = Math.floor(Math.random()*2);
var newimage = rnumb + ".jpg";
if (newimage !== currentimage)
{
document.getElementById("fade").src= newimage;
}
}
function fadein()
{
var fade = document.getElementById('fade');
if(fade.filters.alpha.opacity >= 100 || fade.style.opacity >= 1.0)
{
changeimg(fade.src);
fade.filters.alpha.opacity = 0;
fade.style.opacity = 0;
}
else
{
fade.filters.alpha.opacity += 10;
fade.style.opacity += 0.1;
}
}
function fadetimer()
{
setInterval("fadein()", 500);
}

Categories

Resources