Preload image to change css background from a url link - javascript

I am loading images from my unsplash collection (https://unsplash.com/collections/3132360/dashboard) and changing the background image of the body (through CSS). It works, but there is a delay in the change. Is there a way I can preload the images and maybe even fade them in/out?
I have tried the new Image() of javascript, but that is for HTML images and not CSS.
Thanks in advance :)
Here is the jquery:
$('document').ready(function(){
var x = 0;
loadImage(x);
});
function loadImage(x) {
x +=1;
var image = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;
setTimeout(function() {
imgSwap(image, x);
}, 30000)
}
function imgSwap(image, x){
$('body').css('background-image', 'url(' + image + ')');
loadImage(x);
}

You can add default image to body style in css to show the preload image.
body{
background-image: url("http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/5-1.gif");
background-repeat: no-repeat;
}
https://jsfiddle.net/nimittshah/cwpdsnLy/

This updated code now works, using img.src as the background URL for the CSS refreshes the image as needed. Using just the image variable as the URL does not.
$('document').ready(function(){
var x = 0;
loadImage(x);
});
function loadImage(x) {
x +=1;
var image = new Image()
image.src = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;
setTimeout(function() {
imgSwap(image, x);
}, 30000)
}
function imgSwap(image, x) {
$('body').css('background-image', 'url(' + image.src + ')');
loadImage(x);
}

I think if you can include this following javascript code and css, it might be able to full fill what you want to achieve
function preloader() {
if (document.getElementById) {
document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px";
document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px";
document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }

var x = 0;
$('document').ready(function(){
loadImage(x);
});
function loadImage(x) {
setInterval(function() {
var randomId = new Date().getTime();
var image = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x+'?r='+randomId;
console.log("x="+x + " " + image);
imgSwap(image);
x +=1;
}, 30000)
}
function imgSwap(image){
$('body').css('background-image', 'url(' + image + ')');
//$('#bg_img').attr('src', image);
}
You can change value of x randomly, but i have found your img provider is not returning the images plz check this first, It is redirecting to some other url
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!--<img id="bg_img" src="" width=400 height=400/>-->

Related

Preloading images on safari for background image change [duplicate]

This question already has answers here:
Preloading images with jQuery
(20 answers)
Preload background image
(5 answers)
Closed 5 years ago.
I have a background that changes every 12seconds.
In Chrome, Firefox and Opera the background change is works fine, but in Safari the browser always loads the image again and that is noticed by a flickering on every image change on the first cycle. Any ideas on how can I solve this problem.
This is how I'm handling the background change:
var img2 = new Image();
var img3 = new Image();
img2.src="/img/bg2.png";
img3.src="/img/bg3.png";
Meteor.setInterval(function(){
let elem = $(".header-2");
if(elem.hasClass("bg1")){
elem.removeClass("bg1");
elem.addClass("bg2");
let src = 'url('+img2.src.replace(location.origin,'')+')';
elem.css("background-image", src);
}
else if(elem.hasClass("bg2")){
elem.removeClass("bg2");
elem.addClass("bg3");
let src = 'url('+img3.src.replace(location.origin,'')+')';
elem.css("background-image", src);
}
else{
elem.removeClass("bg3");
elem.addClass("bg1");
}
}, 12*1000)
The css classes:
.header-2.bg1 {
background-image: url('/img/bg1.png');
}
.header-2.bg2 {
}
.header-2.bg3 {
}
Changing the background after an onload event on the image should ensure the image is completely loaded before updating anything on the page.
This approach adds the event and keeps the background changes in JS.
var bgs = ['http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg', 'http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg','http://www.mrwallpaper.com/wallpapers/Huge-Bear.jpg'],
count = 1,
header2 = document.getElementsByClassName('header-2')[0];
setInterval(function() {
var img2 = new Image(),
url = bgs[count];
img2.onload = function() {
header2.style.backgroundImage = 'url(' + url + ')';
}
img2.src = url;
(count < (bgs.length - 1)) ? count++ : count = 0;
},1000)
body {
margin: 0;
}
.header-2 {
background-position: top center;
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
margin: 0;
background-image: url('http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="header-2"></header>
You can also use the same method with your code where you're using CSS to control parts of it. Here I just set a data-bg attribute in your interval, then control the background-image (and whatever else) via CSS using the data selector
var bgs = ['http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg', 'http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg', 'http://www.mrwallpaper.com/wallpapers/Huge-Bear.jpg'],
count = 0,
header2 = document.getElementsByClassName('header-2')[0];
setInterval(function() {
var img2 = new Image(),
url = bgs[count];
img2.onload = function() {
header2.setAttribute('data-bg', count);
}
img2.src = url;
(count < (bgs.length - 1)) ? count++ : count = 0;
}, 1000)
body {
margin: 0;
}
.header-2 {
background-position: top center;
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
margin: 0;
background-image: url('http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg');
}
.header-2[data-bg="1"] {
background-image: url('http://cdn.thedailybeast.com/content/dailybeast/articles/2015/03/31/neil-degrasse-tyson-defends-scientology-and-the-bush-administration-s-science-record/jcr:content/image.img.2000.jpg/1432067001553.cached.jpg');
}
.header-2[data-bg="2"] {
background-image: url('http://www.mrwallpaper.com/wallpapers/Huge-Bear.jpg');
}
<header class="header-2" ></header>
this is possibly due to images not loading properly before the script is being executed by calling the function onload() will do the trick.

change background-image of div with animation

I would like to create a little slider to change background-image of my div every seconds.
My code doesn't work for the moment, image is not changed. And ideally, i would like that the script run in infinite mode..
HTML
<div id="slidesPartenairesHome"></div>
CSS
#slidesPartenairesHome {
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
margin-left: 120px;
}
JS
$( document ).ready(function() {
var arrayOfPartenaires = [
"images/partenaires/a.png",
"images/partenaires/b.jpg",
"images/partenaires/c.jpg",
"images/partenaires/d.png",
"images/partenaires/e.png",
"images/partenaires/f.jpg",
"images/partenaires/g.jpg",
"images/partenaires/h.jpg",
"images/partenaires/i.png",
"images/partenaires/j.jpg",
"images/partenaires/k.jpg",
"images/partenaires/l.jpg"
];
for (var i=0; i<arrayOfPartenaires.length; i++) {
var currentPartenaireImg = arrayOfPartenaires[i];
$('#slidesPartenairesHome').animate({opacity: 0}, 'slow', function() {
$(this).css({'background-image': 'url("'+currentPartenaireImg+')'}).animate({opacity: 1});
});
}
});
You could use window.setinterval, you could also use setTimeout but setinterval is a litle bit more precise.
Example with setinteval:
window.setInterval(function(){
var url = getCurrent();
//start animation
$('#slidesPartenairesHome').delay( 500 ).fadeTo(500, 0.3, function()
{
$(this).css('background-image', 'url(' + url + ')');
}).fadeTo('slow', 1);
}, 1000);
// We start with index of 1 because we want to skip the first image,
// Else we would be replacing it with the same image.
var index = 1;
var arrayOfPartenaires = [
"http://yourdomain.com/images/partenaires/a.png",
"http://yourdomain.com/images/partenaires/b.png",
"http://yourdomain.com/images/partenaires/c.png"
];
function getCurrent(){
// We check if the index is higher than the ammount in the array.
// If thats true set 0 (beginning of array)
if (index > arrayOfPartenaires.length -1){
index = 0;
}
var returnValue = index;
index ++;
return arrayOfPartenaires[returnValue];
}
Note if you really want to change the image every 1 second the background will be changing very fast.
Fiddle
I hope this may help you
html
<div id="slidesPartenairesHome">
<div id="imags">
</div>
</div>
Css
#slidesPartenairesHome
{
margin-left: 120px;
}
#slidesPartenairesHome, #imags
{
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
}
Js
$(function () {
var arrayOfPartenaires = [
"http://fotos2013.cloud.noticias24.com/animales1.jpg",
"http://www.schnauzi.com/wp-content/uploads/2013/03/animales-en-primavera.jpg",
"https://johannagrandac.files.wordpress.com/2015/01/conejos.jpg",
"http://png-4.findicons.com/files/icons/1035/human_o2/128/face_smile.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/128/big-smile-icon.png",
"http://simpleicon.com/wp-content/uploads/smile-256x256.png"
];
var loaders = 0;
function cycleImages() {
var element = arrayOfPartenaires[loaders];
$("#imags").css({ 'background-image': 'url(' + element + ')' }).animate({ opacity: 1 }).hide().fadeIn("slow");
if (loaders < arrayOfPartenaires.length) {
loaders = loaders + 1;
if (loaders >= arrayOfPartenaires.length) {
loaders = 0;
}
}
else {
loaders = 0;
}
console.log(loaders, arrayOfPartenaires[loaders]);
}
cycleImages();
setInterval(function () { cycleImages() }, 3000);
});
jsFiddel Demo

JavaScript dymanically change CSS background style

I am trying to dynamically change my background image by continuously looping through an array of image paths. The code works if I log the output to a console, but I cannot get the image to actually change.
Original CSS: (I am overriding the default style from another CSS file)
<style>
.jumbotron {
background: #7da7d8 url('images/rotunda2.jpg') no-repeat center center !important;
}
</style>
JavaScript:
$(document).ready(function () {
var count = -1;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
setInterval(swap, 5000);
function swap(){
$('.jumbotron').css("background", "#7da7d8 url('"+images[++count % images.length]+"') no-repeat center center !important");
console.log(images[++count % images.length]);
}
});
Any ideas?
You're swap function seems kind of odd. Typically for something like this, you could have a counter that gets incremented and then just resets to 0 and starts over. Also make sure you are running in an onload event handler context.
var count = 0;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
function swap(){
//get the next image
var nextImage = images[count];
console.log(nextImage);
$('.jumbotron').css("background-image", nextImage);
//increment count
count = count > images.length - 1 ? 0 : count+=1;
}
$(document).ready(function(){
setInterval(swap, 5000);
});
aside from that, make sure to check your error console for errors, and for 404's indicating you might have bad image paths
Try this:
$(document).load(function() {
var count = -1;
var images = ['images/image1.jpg', 'images/image2.jpg', 'images/image3.jpg'];
setInterval(swap, 5000);
function swap() {
var img = images[++count % images.length];
$('.jumbotron').css('background', '#7da7d8 url(' + img + ') no-repeat center center !important');
console.log(img);
}
});
I don't think change css is a good idea, you may define some classes, and dynamically change the classes on the element!
html:
<div class="dynamicBg class1"></div>
<div class="dynamicBg class1"></div>
css:
.dynamicBg {
background-color: #7da7d8;
background-repeat: no-repeat;
background-position: center center;
}
.class1 {
background-image: url('images/image1.jpg');
}
.class2 {
background-image: url('images/rotunda2.jpg');
}
.class3 {
background-image: url('images/rotunda3.jpg');
}
.class4 {
background-image: url('images/rotunda4.jpg');
}
js:
$(function() {
var classStr = 'class1 class2 class3 class4',
classArr = classStr.split(' '), i = 0,
$dynamicBg = $('.dynamicBg');
setInterval(function() {
i = i > 3 ? 0 : i + 1;
$dynamicBg.removeClass(classStr).addClass(classArr[i]);
}, 5000);
});
Wait for the document to load:
$(document).load(function()
{
var count = -1;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
setInterval(swap, 5000);
function swap(){
$('.jumbotron').css("background", "#7da7d8 url("+images[++count % images.length]+") no-repeat center center !important");
console.log(images[++count % images.length]);
}
});

Jquery fadeIn not appearing to happen

I have made this minimal test jsfiddle to show images and navigate with thumbnails, next and previous and also run as a slideshow.
It seems to be working OK, except that I can not get the current displayed image to fadeOut prior to the fadeIn of the next image.
Initially all the images were placed in a stack in the #holder DIV and then FadeIn and FadeOut worked as I expected, but I need to have the images in an array and load as required, because there will be several different values, associated with each image.
I probably have made some fundamental mistake or I do not understand how FadeIn and FadeOut properly work, as I am not an expert in javascript and jquery and I just get by, by looking at examples on here and similar sites.
I suspect I may need to somehow force a delay before loading the next image, but I can not work out how to do that.
Thanks
<style type='text/css'>
#holder { position: absolute; top: 100px; background-color:#CCCCCC;
width: 300px; height: 200px;
}
.slides { position: relative; top: 0px;
display: none;
}
#thumbs li
{
display: inline;
list-style-type: none;
padding-right: 6px;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// define Global Vars
var timerON = null;
var files = [
["http://dummyimage.com/300x200/000/fff&text=Array-01", "http://dummyimage.com/40x40/000/fff&text=01","Title-01"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-02", "http://dummyimage.com/40x40/000/fff&text=02","Title-02"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-03", "http://dummyimage.com/40x40/000/fff&text=03","Title-03"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-04", "http://dummyimage.com/40x40/000/fff&text=04","Title-04"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-05", "http://dummyimage.com/40x40/000/fff&text=05","Title-05"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-06", "http://dummyimage.com/40x40/000/fff&text=06","Title-06"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-07", "http://dummyimage.com/40x40/000/fff&text=07","Title-07"]
]
var numImages = files.length;
// initial routines
showImage(1);
buildThumbs();
function showImage(num) {
//$('#holder img').fadeOut();
if ( $('#holder img').length > 0 ) { // fadeout existing
$("#holder img").fadeOut(700);
//alert("Faded OUT");
}
$("#holder").html('<img id="' + num + '" src="' + files[num-1][0] + '" style="display:none;"' + '" />');
$("#holder img").fadeIn(700);
//alert("Faded IN");
}
function buildThumbs() {
var thumbs = "";
for (cnt=0; cnt<files.length; cnt++) {
thumbs += '<li><a href="#" id="' + (cnt + 1) + '"><img src="' + files[cnt][1] + '" /></li>';
}
$('#thumbs').html(thumbs);
}
// Initialise routines for acting on click events
$(document).ready(function() {
$('#prev').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == 1) {
// at first position
}
else {
showImage(currImage-1); }
});
$('#next').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
// at last position
}
else {
showImage(currImage+1);
}
});
$('#thumbs a').click( function () {
var selImage = parseInt($(this).attr('id'));
var currImage = parseInt($('#holder img:visible').attr("id"));
showImage(selImage);
});
$('#slideShowBtn').click( function () {
slideShowCheck();
});
});
function slideShowCheck() {
if(timerON != null) {
clearTimeout(timerON);
timerON = null;
$('#slideShowBtn').text('Play Slideshow');
} else {
$('#slideShowBtn').text('Stop Slideshow');
slideShow();
}
}
function slideShow() {
var nextImage = 0;
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
nextImage = 1;
} else {
nextImage = currImage + 1;
}
showImage(nextImage);
timerON = setTimeout(slideShow, 3000);
}
});//]]>
</script>
</head>
<body>
<p>
<button id="prev">« Prev</button>
<button id="next">Next »</button>
</p>
<ul id="thumbs">
</ul>
<p>
<button id="slideShowBtn">Play Slideshow</button>
</p>
<div id="holder">
</div>
<div style="clear:both;"></div>
<ul id="thumbs2">
</ul>
</body>
</html>
Callbacks, callbacks, callbacks.
JS does alot of things async, so you will need to make use of a callback on that fadein.
$(ITEM1).fadeOut("fast", function() {
alert("all the way faded out");
$(ITEM2).fadeIn("fast");
});
Here's your fixed fiddle.

Animating PNGs using Javascript

<div id="dragon" style="position: absolute; left: 600px; top: 400px; " onload="timeimgs('9');">
</div>
<script language="JavaScript">
var anim_images=new Array();
//putting drag0 to drag9 png into the anim_images array
for (i=0;i<=10;i++) {
var name;
name=eval("drag" + numb + ".png");
anim_images.push("name");
}
function imgturn(numb) {
if (numb == "9") { // This will loop the image
//getting the image of the array when reach 9
document["demo"].src=anim_images[9];
//starting again with drag0.png?
timeimgs('0');
}
else {
document["demo"].src=anim_images[numb];
timeimgs(numb = ++numb);
}
}
function timeimgs(numb) { // Reusable timer
thetimer = setTimeout("imgturn('" +numb+ "')", 1000);
}
</script>
Right now, it isn't working yet. it set the drag0.png to 200 width and 200 height. and I want to animate drag0.png to drag9.png continuously.
Any inputs are appreciated.
HTML:
<div id="dragon" style="position:absolute; left:60px; top:40px; width:640px; height:480px; "></div>
JAVASCRIPT:
function animateImagesStart() {
// next array generation code only for my sample/test: comment it or delete
var imgs=[
"http://4.bp.blogspot.com/-PilKprMNhpo/TVc4rKk_gKI/AAAAAAAAAWo/O3wPK3kIH_8/s640/two_flowers.preview.jpg",
"http://1.bp.blogspot.com/-4-NEunVEZxA/TWendjaBwOI/AAAAAAAAAAU/KKO4MDt5xJ0/s640/10_4_orig.jpg",
"http://4.bp.blogspot.com/-pc9ImOpPTs0/TaxDIYd5JnI/AAAAAAAAA_M/PF8b7H3nCs8/s640/ocean-flowers.jpg",
"http://4.bp.blogspot.com/-3CjVKRE6kXE/Ti_Gy6fXKuI/AAAAAAAAG3k/-er17XD7uJc/s640/cherry-blossom-pink-flowers-3.jpg",
"http://whatscookingamerica.net/EdibleFlowers/LavenderFlowers.jpg",
"http://www.photographyblogger.net/wp-content/uploads/2010/05/flower23.jpg",
"http://1.bp.blogspot.com/_24bCsL1xWcM/S6ob05W5KbI/AAAAAAAAAOQ/ZEQK9aiR-nQ/s1600/Flowers.jpg",
"http://3.bp.blogspot.com/_NjdBzKI5nYs/Sc79kMCKxZI/AAAAAAAABu8/vfk6RrGzpPw/s640/flower+sky+wallpaper+image+photo+pic.jpg",
"http://4.bp.blogspot.com/-ik3E8PBBf70/TwaZ9PMNbrI/AAAAAAAAAG0/kNrGnEbZ-WY/s1600/flowers2.jpg",
"http://www.funeral-flowers-online.com/funeral-flowers.jpg"
];
// next array generation code based on your code: uncomment it
/*
var imgs=[];
for(var i=0;i<10;i++)imgs.push("drag"+i+".png"); // 10 images
*/
// preloading images
var img,count=imgs.length,
imageLoadComplete=function(ev) {
if(ev.type=="error")imgs.splice(imgs.indexOf(this),1);
};
for(var i=0;i<count;i++){
img=new Image();
img.onerror=imageLoadComplete;
img.src=imgs[i];
imgs[i]=img;
}
var domImg=document.getElementById("dragon"),
currentImageIndex=0,
animateImages=function(){
if(currentImageIndex>=imgs.length)currentImageIndex=0;
if(imgs[currentImageIndex].complete)domImg.style.backgroundImage="URL("+imgs[currentImageIndex].src+")";
currentImageIndex++;
setTimeout(animateImages,1000);
};
setTimeout(animateImages,0);
}
if(window.addEventListener)window.addEventListener("load",animateImagesStart,false);
else if(window.attachEvent)window.attachEvent("onload",animateImagesStart);
Insure that each of your images has same size (width and height) as DIV#dragon or replace DIV#dragon with IMG#dragon html element and use IMG src property instead of style.backgroundImage. Example: http://jsfiddle.net/RK7u9/1/

Categories

Resources