Preload background images - javascript

I am cycling through background images in javascript/jQuery like this...
var duration = 2500;
var delay = 500;
var i = 0;
setInterval(function() {
if (i == 0) {
$(".myimage").css("background-image", "url('https://placeimg.com/1640/1480/any')");
}
if (i == 1) {
$(".myimage").css("background-image", "url('https://placeimg.com/1640/1481/any')");
}
if (i == 2) {
$(".myimage").css("background-image", "url('https://placeimg.com/1640/1482/any')");
}
if (i == 3) {
$(".myimage").css("background-image", "url('https://placeimg.com/1640/1483/any')");
}
i++;
}, duration + delay)
.myimage {
height: 500px;
width: 500px;
transition: background-image 1s linear;
background-image: url('https://placeimg.com/1648/1488/any');
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myimage">
</div>
Problem is, I get flashes of no image occasionally, I think this is down to the images not being loaded in time. Is there a way to preload them?

You could preload them using CSS like:
body::after{
position:absolute; width:0; height:0; overflow:hidden; z-index:-1;
content:url(https://placeimg.com/1640/1480/any) url(https://placeimg.com/1640/1481/any) url(https://placeimg.com/1640/1482/any) url(https://placeimg.com/1640/1483/any);
}
NOTE: You could use an array of images in the JS code and change them based on the index i.
var duration = 2500;
var delay = 500;
var i = 0;
var images = ['https://placeimg.com/1640/1480/any', 'https://placeimg.com/1640/1481/any', 'https://placeimg.com/1640/1482/any', 'https://placeimg.com/1640/1483/any'];
setInterval(function() {
$(".myimage").css("background-image", "url(" + images[i] + ")");
i++;
}, duration + delay)
.myimage {
height: 500px;
width: 500px;
transition: background-image 1s linear;
background-image: url('https://placeimg.com/1648/1488/any');
background-size: cover;
}
body::after {
position: absolute;
width: 0;
height: 0;
overflow: hidden;
z-index: -1;
content: url(https://placeimg.com/1640/1480/any) url(https://placeimg.com/1640/1481/any) url(https://placeimg.com/1640/1482/any) url(https://placeimg.com/1640/1483/any);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myimage">
</div>

You can preload the images as followed
function preloadImages(){
var images = ["https://placeimg.com/1640/1480/any","https://placeimg.com/1640/1481/any","https://placeimg.com/1640/1482/any","https://placeimg.com/1640/1483/any"];
var prelaodedImages = [];
for(i=0;i<images.length;i++){
prelaodedImages[i] = new Image();
prelaodedImages[i].src = images[i];
console.log(prelaodedImages[i].src)
}
}
preloadImages();
After the images are preloaded you can use your code and instead of
"url('https://placeimg.com/1640/1480/any')")
You use
"url("+prelaodedImages1.src+")")
This should normally result in your images already being loaded and displaying correctly.

For the first time, browser needs to download all the images, once downloaded, it'll load from cache.
So, flashes of no image will come every time whenever browser download file. you have two options
the approach you are following (which is ok)
Use CSS trick to load all at once by using following code
.myimage {
height: 500px;
width: 500px;
transition: background-image 1s linear;
background-image: url('https://placeimg.com/1648/1480/any');
background-image: url('https://placeimg.com/1648/1481/any');
background-image: url('https://placeimg.com/1648/1482/any');
background-image: url('https://placeimg.com/1648/1483/any');
background-size: cover;
}

Once browser loads it, it wont be reloaded all the time. the second time the same image is rendered there wont be such issue,
make the image cycle using i= i==3?0:++i.
Rather than just i++
Fiddle

Related

Preloaded images flash at different rates

I'm calling images from a folder at random and putting them in HTML img tags using PHPs glob function.
I'm then using JS to read the URLs and flip the CSS background image of div#wrapper, 300ms for each image. The images should be preloaded as they have HTML img tags. They are being hidden from the user using the following CSS (which should not stop preloading as "display: none" does):
.visuallyhidden {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px; width: 1px;
margin: -1px; padding: 0; border: 0;
}
Nonetheless I'm experiencing the images flashing inconsistently / at different rates. It seems that larger file size images cause this to happen, but the images should be preloaded so I'm not sure why this is occurring.
My JS looks like this:
var slides = [];
$('.slide').each(function(index){
slides.push($(this).attr('id'));
});
var slide = 0;
function changeImage(){
if (slide < 10){
var currentSlide = $("#" + slides[slide]);
$('#wrapper').css('background-image', '');
$('#wrapper').css('background-image', 'url("' + currentSlide.attr('src') + '")');
slide++
} else {
$('#headline').removeClass('visuallyhidden');
$('#wrapper').css('background-image', '');
$('#wrapper').css('background-color', '#ef3308');
}
}
setInterval(changeImage, 300);
The site is http://robertirish.com.
Is there a better way to do this / can anyone explain why it's happening?
I'm going to guess it's a loading issue: either that CSS is interfering with preload or else it's being treated differently because you're loading it into the background of another element rather than using the img that you preloaded. Instead, I would load all the images inside the div, absolute-positioned on top of each other, and then just remove them one by one:
CSS:
#wrapper{
position: relative;
}
#wrapper img{
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
HTML:
<div id="wrapper">
<img src="image1.png">
<img src="image2.png">
<!--etc-->
</div>
JS:
$(document).on('ready', function(){
var images = [];
$("img", "#wrapper").each(function(){
images.push(this);
});
var timer = setInterval(function(){
if (images.length)
$(images.pop()).remove();
else
clearInterval(timer);
}, 300);
});

Image Carousel with Fade to Black Transition

I need to make a carousel with a fade transition that goes black, or even better some dark grey color like #2B303A. I've found this code on the web that works perfectly, the only problem is that the fade effect is a really bright white that I don't like and it's bothering for the eyes.
How can I make it fade to black between images?
$(document).ready(function() {
//Carousel
var vet_url = ["https://i.imgur.com/Bb39Qpp.jpg", "https://images.wallpaperscraft.com/image/palms_road_marking_123929_1920x1080.jpg"];
var len = vet_url.length;
var i = 0;
function swapBackgrounds() {
$("#background").animate({
opacity: 0
}, 700, function() {
$($("#background")).css('background-image', 'url(' + vet_url[(i + 1) % len] + ')').animate({
opacity: 1
}, 700);
});
i++;
}
setInterval(swapBackgrounds, 10000);
});
#background {
background-color: #2B303A;
position: absolute;
z-index: 1;
min-height: 100%;
min-width: 100%;
background-image: url("https://images.wallpaperscraft.com/image/palms_road_marking_123929_1920x1080.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="background"></div>
View on JSFiddle
you need to do it on the html element, in your test case at least.
html
{
background-color:#2B303A;
}
Setting the opacity to 0 let you see the element underneath the carousel, in this case there's nothing but the body itself. The background-color of the body wasn't set so it was the default white one. Setting the background-color to black solved the problem.
jquery's .animate does not work with background-colors though it can work with:
https://github.com/jquery/jquery-color

jQuery slider fade effect without white areas

Heyo,
I'm currently working on a background slider but I can't make it work as I want it to work.
So what I need is a fade-effect which produces no white space between the images.
So ... the following image should fadeIn but the current image should just stay and fadeOut when the fadeIn effect of the following image is done. (If that makes sense)
This is the current script I'm using:
$(document).ready(function(){
var count = 1;
var images = [ "http://i.imgur.com/HX0X6lV.png", "http://i.imgur.com/N50Ye7i.png", "http://i.imgur.com/TFG5oaa.png"];
var image = $(".background");
setInterval(function(){
image.fadeOut(500, function(){
image.css("background-image","url("+images[count++]+")");
image.fadeIn(500);
});
if(count == images.length)
{
count = 0;
}
},3000);
});
.background {
position: absolute;
width: 100%;
height: 100%;
top:0;
left:0;
background-size: cover;
background-position: center center;
background-image: url("http://i.imgur.com/HX0X6lV.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="background"></div>

How to change bootstrap header image every x second?

I am designing a bootstrap based website. I have a navigation bar and below it there is a full screen background image. I want to change the the background image after some seconds. The image is inside a header tag and has some text over it in the center. The code for header:-
<header id="image">
<div class="header-content">
<h1>Hello</h1>
</div>
</header>
The css for header:-
header {
position: relative;
width: 100%;
min-height: auto;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
background-position: center;
background-image: url('images/1.jpg');
text-align: center;
color: white;
}
.header1 {background-image: url('images/1.jpg');}
.header2 {background-image: url('images/2.jpg');}
.header3 {background-image: url('images/3.jpg');}
The javascript i tried:-
<script type="text/javascript">
function run(interval, images) {
var int = 1;
function func() {
var d = document.getElementById("image");
d.className += "header"+int;
int++;
if(int === images) { int = 1; }
}
var swap = window.setInterval(func, interval);
}
run(5000, 3);
</script>
I tried to change the class property after an interval but it didn't work.
I want to change the background-image of the header lets say after every 10 seconds to 2.jpg and then to 3.jpg and then back to 1.jpg using plain javascript. Please provide a way as i am unable to think of a way to change the image. I would be highly grateful if anyone can help.
This will take care of what you are looking for, assuming that your images are named with digits.
var counter = 1; //instantiate a counter
var maxImage = 5; //the total number of images that are available
setInterval(function() {
document.querySelector('header').style.backgroundImage = "url('images/" + (counter + 1) + ".jpg')";
if (counter + 1 == maxImage) {
counter = 0; //reset to start
} else {
++counter; //iterate to next image
}
}, 10000);

js backgroundImage() fade in on load?

I'm using javascript to display my background image because I'd like to have a random background image on each reload. Anyway, because of this my typical CSS transitions and animations won't do, because instead of fading the background it fades the text inside of my body.
Is there any way around this so that on each reload the background fades in?
This is the code I am using to display the random image:
var randomImage = Math.floor(Math.random() * 18) + 1;
document.body.style.backgroundImage = "url(images/" + randomImage + ".jpg)";
and I'm unsure how to make it fade in... any thoughts?
Using: https://css-tricks.com/snippets/css/transparent-background-images/
http://jsfiddle.net/wby2xf6f/1/
div {
width: 200px;
height: 200px;
display: block;
position: relative;
}
div:after {
transition: opacity 5s;
content: "";
background: url(http://www.wina.ugent.be/style/img/h1.png);
opacity: 0;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
div.fadein:after {
opacity:1;
}
And then add the class .fadein with Javascript/JQuery.
http://jsfiddle.net/wby2xf6f/1/
On a sidenote: it might be better to select the background-image at random on the server side (using php/ruby/whatever).
Updated, but less semantic version: http://jsfiddle.net/wby2xf6f/5/
.fill {
position:absolute;
height:100%;
width:100%;
z-index:-1;
display:none;
background:url(http://www.wina.ugent.be/style/img/h1.png);
}
$('.fill').fadeIn(5000)
This example with your code above
$(document).ready(function(){
var img1 = "http://www.clarkcraft.co.uk/images/des/48040.jpg";
var img2 = "http://glamorouslymommy.com/wp-content/uploads/2013/05/small-background1.jpg";
setInterval(function(){
var randomImage = Math.floor(Math.random() * 18) + 1;
if(randomImage<=5){
$("div").css("background","url("+img2+")").show().fadeOut("slow"); $("div").css("background","url("+img1+")").show().fadeIn("slow");
}
else{
$("div").css("background","url("+img1+")").show().fadeOut("slow"); $("div").css("background","url("+img2+")").show().fadeIn("slow");
}
}, 1000);
});
div {
width:200px;
height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="display:none"></div>

Categories

Resources