JavaScript header background fade - javascript

I am trying to get one background image to fade into another using a very simple if statement. Currently my background images do not fade into one and another, they first fade onto a white background and then the other image fades in after, I would however like them to fade into each other directly. Secondly there seems to be an error with my images displaying, so when the the limit of the array (1) is reached in the if statement then it will set a simple currentBackground variable to 0, meaning the backgrounds should start from 0 in the array, however, this does not happen and sometimes the image same image is displayed repetitively.
$(window).load(function() {
var images = ['img/fitness-bg-2.jpg','img/runner-header.jpg'];
var i = 0;
function changeBackground() {
$('#header').fadeOut(250, function(){
$('#header').css('background-image', function () {
if (i >= images.length) {
i = 0;
}
return 'url(' + images[i++] + ')';
});
$('#header').fadeIn(500);
})
}
changeBackground();
setInterval(changeBackground, 5000);
});

Related

How can I animate a recently created DOM element in the same function?

I'm working to create an image gallery where the images will be composed by progressively fading in layers one on top of the other to form the final image.
I have many such layers so instead of loading them into many different <img> elements all at once (which would slow load time) I want to start off with a single <img id="base"> and then progressively add image elements with the jQuery .after() method, assign them the relevant sources and fade them in with a delay.
The problem is that I can't attach animations to the newly created elements because (I'm assuming) they don't exist yet within the same function. Here is my code:
HTML
<div id="gallery">
<img id="base" src="image-1.jpg">
</div>
CSS
#base {
opacity: 0;
}
.layers {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
JavaScript
$(document).ready(function () {
$("#base").animate({opacity: 1}, 300); //fade in base
for (var i = 1; i <= numberOfLayers; i++, gap += 300) {
// create a new element
$("#base").after("<img class='layers' src='" + imgName + ".png'>");
// fade that new element in
$("#gallery").children().eq(i).delay(gap).animate({opacity: '1'}, 300);
}
}
Please note that I've altered my actual code to illustrate this better. I'm fairly new at JavaScript but I'm a quick learner so I'd appreciate if you could tell me what I'm doing wrong and what solution I should pursue.
EDIT: I've included my code inside your JSFiddle (all you need to do is add the library-X.jpg images) : http://jsfiddle.net/pgoevx03/
I've tried to replicate the intent of the code in a cleaner/more flexible way. Please let me know if I can do anything else to help.
I'm not saying this is the best way to do it, but it should be easy enough to understand and use.
The code is untested, but should work just fine. The comments should help you out if there's any compilation error.
Note that I removed the first image in the gallery (with ID "base") from the HTML file. It will be appended the same way as the rest.
// Array storing all the images to append to the gallery
var galleryImages = [
"image-1.jpg",
"image-2.jpg",
"image-3.jpg",
"image-4.jpg",
"image-5.jpg",
"image-6.jpg",
"image-7.jpg",
"image-8.jpg",
"image-9.jpg",
"image-10.jpg"
];
// Index of the image about to be appended
var imgIndex = -1;
var baseID = "base";
$(document).ready(function() {
// Start appending images
appendAllImages();
});
// Append the images, one at a time, at the end of the gallery
function appendAllImages() {
//Move to the next image
imgIndex++;
//We've reached the last image: stop appending
if (imgIndex >= galleryImages.length) return;
//Create image object
var img = $("<img>", {
src: galleryImages[imgIndex],
});
if (imgIndex === 0) { // It's the base!
//Give the base ID to the first image
img.attr("id", baseID);
//Append the image object
$("#gallery").append(img);
} else { // It's a layer!
//Give the base ID to the first image
img.attr("class", "layers");
//Append the image object
$("#" + baseID).after(img);
}
//Fade in the image appended; append the next image once it's done fading in
img.animate({
opacity: 1,
}, 300, appendAllImages);
}

adding fade to change background with javascript

I have the following code for changing a divs background image with jquery, i need help to add a fade to the code so the image change with some effect
this is the code
jQuery(window).load(function(){
var images = ['blured/1.jpg','blured/2.jpg'];
var i = 0;
var timeoutVar;
function changeBackground() {
clearTimeout(timeoutVar); // just to be sure it will run only once at a time
jQuery('#maincont').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
// call the setTimeout every time to repeat the function
timeoutVar = setTimeout(changeBackground, 6000);
}
// Call it on the first time and it will repeat
changeBackground();
});
Any help will be great!
i need to just change the background image, without fading the inside divs, this is the html
<div class="maincont" id="maincont">
<div class="containersrch">
<h1 class="lagro">some title</h1>
<div class="joinus">
<span>JOIN</span>
</div>
</div>
Maybe this is what you want?
$(function(){
var imgId = $('#maincont'), imgCount = 1, imgLast = 2;
setInterval(function(){
imgId.fadeOut('slow', function(){
if(++imgCount > imgLast)imgCount = 1;
imgId.css('background', "url('blured/"+imgCount+".jpg')");
imgId.fadeIn('slow');
});
}, 6000);
});
Now you can have multiple images, just change imgLast to the last number and make sure they have the correct URLs in your blured folder. Of course, the code above assumes you are using .jpg. I actually recommend the lossless compression of .png, but it won't matter if it's the image was taken as a .jpg.

Simple loop for images

I'm trying to build a simple image slider (but using a fade effect). Every two seconds, the image should change to another image. At the end, it should call repeat_sponsor() again, to start over, so it becomes a loop.
I've written this (highly ineffective) code for 5 images. Turns out I'm going to need it for around 50 images. My editor just freezes when I add too much code.
I've tried using while-loops, but I just can't figure it out how to do this the right way.
Anyone who can help me with this?
function repeat_sponsor()
{
$("#sponsor2").hide();
$("#sponsor3").hide();
$("#sponsor4").hide();
$("#sponsor5").fadeOut("slow");
$("#sponsor1").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor2").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor3").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor4").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor5").fadeIn("slow", ...
(function (){
var cnt = 50; //set to the last one...
var max=50;
function show() {
$("#sponsor" + cnt).fadeOut("slow"); //if you want the fadeout to be done before showing next, put the following code in the complete callback
cnt++;
if(cnt>max) {
cnt=1;
}
$("#sponsor" + cnt).fadeIn("slow");
window.setTimeout(show, 2000);
}
show();
})();
But the real issue is the fact you are loading tons of images from the start. You will be better off changing it so you only have a small subset of images and change the source.
You should use some sort of for loop and a class for hiding the images. and add a max value that if checks out resets c & i
var i=0;
var c=1;
function repeat_sponsor()
{
$("#sponsor"+i).fadeOut("slow");
$(".sponsers").hide()
$("#sponsor"+c).fadeIn("slow", function() {
window.setTimeout(repeat_sponsor(), 3000);
}
i++;
c++;
}
Just run a function every two seconds with setInterval and appropriately target your different sponsor divs:
var i = 1;
var max = 50;
setInterval(function() {
// Could target all other sponsor images with a class "sponsor"
$('.sponsor').fadeOut();
// Execute code on the target
$("#sponsor" + i).fadeIn();
if (i === max) {
i = 0;
}
i++;
}, 2000);

Creating Image slider using only jQuery

I'm trying to create an image slider using Jquery.
What I have is a main div with 3 sub divs with images.
Take a look at this fiddle. FIDDLE
Ok now i got the design just the way I want it. What is missing is the functionality.
When i hover over the div or the images, I want it to act like a clockwise slider.
This may look a bit confusing. Take a look at this demo. This is what i want.
DEMO
This is what i want.The right div gets filled with the middle image src , the middle div gets the left div src. The left div get an new src from an array of images i have defined. Currently i can only change one image div at a time.
However I don't want to use any more plugins. Only Jquery plugin. A CSS only solution would be the best but I do not think it will be possible.
JQUERY
$('.maindiv img').mouseover(function () {
var image = this;
loop = setInterval(function () {
if (i < images.length - 1) {
i++;
$(image).attr('src', images[i]);
} else {
i = 0;
$(image).attr('src', images[i]);
}
}, 1500);
EDIT: I managed to get one part of this working. CHECK THIS.Just need to add fade effect Now the problem is after the images in the array end the first images dont loop back... Had not thought of this before.Does Anybody know how i can get over this issue?
Mabye something like this:
jQuery(document).ready(function () {
var images = [];
var loop;
var i = 0;
images[0] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1GfA01TRDgrh-c5xWzrwSuiapiZ6b-yzDoS5JpmeVoB0ZCA87";
images[1] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQSyUWiS4UUhdP1Xz81I_sFG6QNAyxN7KLGLI0-RjroNcZ5-HLiw";
images[2] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_E_OgC6RiyFxKtw03NeWyelfRgJ3Ax3SnZZrufNkUe0nX3pjQ";
$('img', '.maindiv').mouseover(function () {
//Get divs inside main div and reverse them, so right is first
var divs = $($('div','.maindiv').get().reverse());
//Set up loop
loop = setInterval(function(){
divs.each(function(key, div){
if (divs[key+1])
{
//All divs gets image src from previous div > img
$('img', div).attr('src', $('img', $(divs[key+1])).attr('src'));
}
else
{
//This is left div
if (images && images[i])
{
//If picture url not in array then add it
if ($.inArray($('img', div).attr('src'), images) == -1)
{
images.push($('img', div).attr('src'));
}
$('img', div).attr('src', images[i]);
i++;
if (i>= images.length) i = 0;
}
}
});
}, 1500);
}).mouseout(function(){
clearInterval(loop);
});
});
Fiddle

Slideshow Background <body> tag

When a user loads my page I want to let the background color be white then after 5 seconds fade away the color and fade in the picture. And after 5 seconds fade in another picture again so you can create sort of a slide show in the background behind my content. This is what I have now but it doesn't work, any help?
$(document).ready(function() {
setTimout(function() {
$('body').css("background-image","url('../img/background/1.jpg')").fadeIn(1000)
},5000);
function repeat() {
$('body')
.delay(5000).css("background-image","url('../img/background/2.jpg')").fadeIn(1000)
.delay(5000).css("background-image","url('../img/background/3.jpg')").fadeIn(1000)
.delay(5000).css("background-image","url('../img/background/1.jpg')").fadeIn(1000);
}
window.setInterval(repeat, 18000);
});
The following is a syntax error:
setTimout(function() {
$('body').css("background-image","url('../img/background/1.jpg')").fadeIn(1000)
},5000);
Should be
setTimeout(function() {
$('body').css("background-image","url('../img/background/1.jpg')").fadeIn(1000)},5000);
It is missing the e in setTimeout
I also do not believe you will be able to fadeIn the background image unless you are setting it on a DIV unless you fadeOut the body. I have re-written your background changer into fewer lines of code that repeat with a list of images provided. This should keep looping for the images you have in the array.
$(document).ready(function () {
var images = ["../img/background/1.jpg", "../img/background/2.jpg"];
var index = -1;
window.setInterval(function () {
index = (index + 1 < images.length) ? index + 1 : 0;
$('body').css("background-image", "url('" + images[index] + "')");
}, 5000);
});

Categories

Resources