Jquery to let my banner images load first before it animates - javascript

I have created a banner image slideshow in jquery. Actually I just found the code somewhere, I can't remember. It starts to animate even the banner images are not yet fully loaded that makes the banner slideshow animates it's image description without images.
Anyone? please help me to modify the code and let it run by allowing the background images load first before it runs the slideshow animation.
Thank you.
(function ($) {
// Original JavaScript code.
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'http://www.site.com/sites/all/themes/layoutph/images/bg01.jpg';
backgrounds[1] = 'http://www.site.com/sites/all/themes/layoutph/images/bg02.jpg';
backgrounds[2] = 'http://www.site.com/sites/all/themes/layoutph/images/bg03.jpg';
backgrounds[3] = 'http://www.site.com/sites/all/themes/layoutph/images/bg04.jpg';
var customtitle = [];
customtitle[0] = "Welcome to Site";
customtitle[1] = "Site joined force with Site Foundation";
customtitle[2] = "Site Foundation school campaigns for 2014";
customtitle[3] = "New York visited by Site Foundation";
function changeBackground() {
if(currentBackground > 3 ) currentBackground = 0;
currentBackground++;
$('.masterbg').fadeOut(1000,function() {
$('div.slogan').text( customtitle[currentBackground] );
$('.masterbg').css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$('.masterbg').fadeIn(1000);
});
setTimeout(changeBackground, 4000);
}
setTimeout(changeBackground, 4000);
})(jQuery);

var UserimageObj = new Image();
UserimageObj.src = "someimg.jpg";
//load the user image before doing anything
UserimageObj.onload = function () {
//do your stuff here
};
Is this what you were looking for?

Related

jquery: How do i fade in on load each image in an array of images?

I'm really new to Jquery, however, i've done research and tried hard to do this. I have successfully made one image to do what i want:
preload the image( img = new Image(); $(img).attr('src', someurl);)
append it to a container
fade in the image ( using .hide() and .fadeIn(500) )
on load add some class and hide a .gif image with the loading animation
using this code:
var img = new Image();
$(img).attr('src', 'images/thumbnails/thumb1.png').attr('alt', 'thumbnail' + 1);
$(img).appendTo($('.thumbnail')).hide().fadeIn(400);
$('.thumb img').load(function(){
$('.loader').fadeOut(300);
$(this).addClass("thumbimage");
});
where .loader is class added to a div that shows the loading.gif animation.
Now, what i want to achieve is to implement this on an array of image srcs and this is what i have so far:
var imagesrc = [ someurl, someurl, ... ];
$(document).ready(function(){
var arr = new Array();
function loadimage() {
for (i = 0; i < imagesrc.length; i++) {
arr[i] = new Image();
$(arr[i]).attr('src', imagesrc[i]);
$(arr[i]).attr('alt', 'thumbnail' + i);
$(arr[i]).hide().appendTo($('.thumbnail').eq(i)).fadeIn(300);
}
}
loadimage();
$('.thumbnail img').load(function(){
var par = $(this).parent();
var row = par.parent();
var indexrow = row.index('.thumbrow');
var thumbindex = par.index('.thumb') + 3*indexrow;
//^ this calculates which loading.gif div to fade out
$('.loader').eq(thumbindex).fadeOut(200);
$(this).addClass("thumbimage");
});
});
I've also tried to move the .append() into the .load(..) and failed.
['url1', 'url2'].forEach(function(imageUrl){
var img = new Image();
$(img).attr('src', imageUrl).attr('alt', 'thumbnail' + 1);
$(img).appendTo($('.thumbnail')).hide().fadeIn(400);
$('.thumb img').load(function(){
$('.loader').fadeOut(300);
$(this).addClass("thumbimage");
});
});
There may be some confusion with ".thumbnail img", "thumbimage". and "thum img". Are all three separately being used correctly, as you laid them out?
At the end, instead of "thumbimage" in $(this).addClass("thumbimage"); you may want to use "thumb img".

How to preload images during a looped array for background images

I've written a simple loop that cycles through a series of images in an array into the background-image property of an element. The problem is that due to the fact that the images are loading, the animation is going haywire when everything is initially loading. I'm trying to set up a preloading workflow where:
the entire loop is blocked by waiting until the first image is fully loaded
every time a new image is fully preloaded, it begins preloading the following image
the preloading must stop when the array is over and use cached images so it's easy on the browser and doesnt just keep loading the same array on images over and over eternally.
Any help?
http://codepen.io/jeremypbeasley/pen/JoZzyo?editors=001
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
var p = photoSet.length;
console.log(p);
var i = 1;
function loopPhotos() {
setTimeout(function() {
$('div').css({'background-image': 'url(' + photoSet[i] + ')',});
i++;
console.log(i);
// call the next indexed image and begin to preload it
var img = new Image();
img.src = photoSet[i];
if (i >= p) {
i = 0;
// stop preloading images, somehow used images that are cached so the browser isn't working eternally reloading the same X number of photos.
}
loopPhotos();
}, 2000)
}
$(document).ready(function() {
// load first image
var firstImg = new Image();
firstImg.src = photoSet[0];
// when first image is loaded, apply it to background and begin looping
if (firstImg.complete) {
$('div').css({'background-image': 'url(' + firstImg.src + ')',});
loopPhotos();
console.log('first image loaded!');
}
});
This will do it
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
function preloadImageAndAct(src, action){
var img = new Image();
img.onload = action;
img.src = src;
}
function showImage( src ){
$('div').css({
'background-image': 'url(' + src + ')',
opacity: 1
});
}
var nextImage = 0;
function loopPhotos() {
console.log('Preload and show image #', nextImage);
var nextSrc = photoSet[nextImage];
preloadImageAndAct( nextSrc, function(){
showImage( nextSrc );
setTimeout( function() {
nextImage++;
nextImage %= photoSet.length;
loopPhotos();
}, 2000);
});
}
$(document).ready(function() {
loopPhotos();
});
Demo at http://codepen.io/gpetrioli/pen/rarPay
Keep in mind that you cannot transition the background-image. If you want transition for the change of images you need to either use two elements or fade the element out / change src / fade the element in.
AS for the caching, once they have been loaded once they are automatically cached by the browser so there should be no issue with that.

Images not preloaded properly

I am having a jQuery script that loads 15 images and their hover versions (the hover versions are used when... hovering, not when the page loads). In both Chrome and Firefox in the Network tab, i see this :
images/img1.png
images_hover/img1.png
This must mean the hover images are preloaded correctly, but... when i actually hover and those images are used, they are being loaded again. Here is the preload code :
var prel = new Image();
prel.src = "http://hdodov.byethost15.com/color-game/graphics/parts_hover/" + id + ".png";
I tried using the whole path - http://hdodov.byethost15.com/color-game/graphics/parts_hover/ and the short path too (where the root and the script is) - graphics/parts_hover/. It made no difference.
Could this be caused because my images have the same name? They are in different directories though.
For the next question, you really should paste more code, which makes it easier to help you. I checked your URL you provided, but for other people that might have the same problem, it will be hard to understand what went wrong...
OK, as I said, you are always requesting he images again on hover state...
This worked for me:
var context = new Array(15),
canvas = new Array(15),
canvasNum = -1,
hElem,
hElemPrev,
mousePos = {x:-1, y:-1},
images = [], //<-- Store preloaded images here
imagesHover = []; //<-- Store preloaded images here
... then save them on building like this:
function drawMenuItems(id, width, height){
var canNumHolder, createCanvas;
$('#canvas_holder').append($('<canvas></canvas>')
.attr({
width:width,
height:height,
id:id
})
);
canvasNum++;
canvas[canvasNum] = document.getElementById(id);
context[canvasNum] = canvas[canvasNum].getContext('2d');
canNumHolder = canvasNum;
images[id].crossOrigin = 'Anonymous';
images[id].onload = function(){
context[canNumHolder].drawImage(images[id],0,0);
};
images[id].src = 'graphics/parts/' + id + '.png';
//Hover states
imagesHover[id] = new Image();
imagesHover[id].src = "graphics/parts_hover/" + id + ".png";
}
... give just the id...
function hoverStateChange() {
//....rest of the code
if(hElem >= 0){
drawImageOnCanvas(
canvas[hElem],
context[hElem],
"hover", //pass somethink to checke what you want to do
$(canvas[hElem]).attr('id')
);
//....rest of the code
//change to normal texture
if(hElemPrev >= 0){
drawImageOnCanvas(
canvas[hElemPrev],
context[hElemPrev],
"", //pass empty for other state
$(canvas[hElemPrev]).attr('id')
);
$(canvas[hElemPrev]).removeClass('active');
$('#text_holder').removeClass('a' + hElemPrev);
}
.. and finally
function drawImageOnCanvas(canv, contxt, state, src){
contxt.clearRect(0,0,400,400);
if(state == "hover"){
contxt.drawImage(imagesHover[src],0,0);
}else {
contxt.drawImage(images[src],0,0);
}
}
Like this, you chache you images and not calling them again and again...
I hope it helps.
Yuo can preload images with css like this:-
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }

Delay image loading with JavaScript

i currently need to load 123,543 images from my server but every image must go through a PHP script to generate it, the problem is that my server is very weak and it crashes after loading about 600 images, so i'm asking for a Javascript that will load 2 images / second, if possible.
Thank you.
You can use http://www.appelsiini.net/projects/lazyload
$(function() {
$("img.lazy").lazyload({
event : "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() { $("img.lazy").trigger("sporty") }, 5000);
});
Assuming you want to place all the images in a container with id 'container', this code does the trick:
var images = [
'image1.jpg',
'image2.jpg'
],
container = document.getElementById('container');
function loadNextImage(index) {
var index = index || 0,
imageUrl = images[index],
image = document.createElement('img');
image.src = imageUrl;
container.appendChild(image);
if (index + 1 < images.length) {
setTimeout(function(){loadNextImage(index + 1)}, 500);
}
}
loadNextImage();

Banner rotator giving "loading" message in browsers

I have this banner rotator function:
var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; //here put location of the files to display
var loadedImgSrc = null;
function loadBanner() {
var liczba = Math.floor(Math.random()*banners.length);
loadedImgSrc = banners[liczba];
var objImage = new Image();
objImage.onLoad=imagesLoaded();
objImage.src = banners[liczba];
}
function imagesLoaded() {
document.getElementById('ad_banner').src = loadedImgSrc;
startRotator();
}
function startRotator() {
setTimeout('loadBanner()',8000); //here, set up interval in miliseconds 1000ms -> 1s
}
This is giving a "loading" message, as if the browsers are continuously loading.
Does anybody have a simple banner-rotator to share?
Or does anybody know whats wrong with this one?
Thanks
Take a look at this custom animated banner made with jQuery. There are both horizontal and vertical versions.

Categories