Weird counter behaviour when integrate on script - javascript

Ok i have finish this code
http://jsfiddle.net/xHL35/9/
I just made some css changes, and rename image_wrap to image_wrap_galeria
here http://queretaro.orsilin.com.mx/index.php?page=item/view/15/Probando
But the counter is really not counting the imgs on .items.
I really tried to debug this one. i cant find the mistake
Here is my JS code.
<script>
$(function() {
$(".scrollable").scrollable();
var scrollapi = $(".scrollable").data('scrollable');
$(".items img").click(function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap_galeria").fadeTo("medium", 0.5);
var wrap2 = $("#mainim");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap2.find("img").attr("src", url);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").click();
$("img[rel]").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ebecff',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: true,
onBeforeLoad: function() {
var items = $('.items'),
count = items.find("img").length,
current = items.find('.active'),
currentIndex = current.index("img");
$("#imageCounter").html( currentIndex+" of "+count);
}
});
//NExt BTN
$(".nextImg").click(function(){
// Count all images
var items = $('.items'),
images = items.find('img'),
count = images.length,
currentImage = items.find('.active'),
currentImageIndex = images.index(currentImage),
next = $(images.get(currentImageIndex + 1)),
nextImageIndex = images.index(next);
if ( currentImageIndex === (count - 1) ){
next = $(images.get(0));
nextImageIndex = images.index(next);
}
if (nextImageIndex === 0) {
scrollapi.begin(200);
} else if ( nextImageIndex % 4 === 0 && nextImageIndex > 0) {
scrollapi.next(200);
}
// Get the current image number
var current = $(next.index("img"));
var nextUrl = next.attr("src").replace("t_", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap_galeria").fadeTo("medium", 0.5);
var wrap2 = $("#mainim");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", nextUrl);
wrap2.find("img").attr("src", nextUrl);
};
// begin loading the image from www.flickr.com
img.src = nextUrl;
$("#imageCounter").html((nextImageIndex + 1) +" of "+count);
// activate item
$(".items img").removeClass("active");
next.addClass("active");
});
//PREV BTN
$(".prevImg").click(function(){
// Count all images
var items = $('.items'),
images = items.find('img'),
count = images.length,
currentImage = items.find('.active'),
currentImageIndex = images.index(currentImage),
prev = $(images.get(currentImageIndex - 1)),
prevImageIndex = images.index(prev);
// var prev = $(".items").find(".active").prev("img");
if(currentImageIndex === 0){
prev = $(images.get(count-1));
prevImageIndex = images.index(prev);
}
if(prevImageIndex === (count - 1)) {
// We have reached the end - start over.
scrollapi.end(200);
} else if ( (prevImageIndex + 1) % 4 === 0 ) {
scrollapi.prev(200);
}
// Get the current image number
var current = (prev.index("img"));
var prevUrl = prev.attr("src").replace("t_", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap_galeria").fadeTo("medium", 0.5);
var wrap2 = $("#mainim");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", prevUrl);
wrap2.find("img").attr("src", prevUrl);
};
// begin loading the image from www.flickr.com
img.src = prevUrl;
$("#imageCounter").html((prevImageIndex + 1) +" of "+count);
// activate item
$(".items img").removeClass("active");
prev.addClass("active");
});
});
</script>

Related

Preload image with Javascript and CSS

I have a big problem with images in javascript embedded aplications. I want make a preload image but I don't know how the browser works.
See this simple example: code
var colors = [
"http://www.robolaranja.com.br/wp-content/uploads/2014/10/Primeira-imagem-do-filme-de-Angry-Birds-%C3%A9-revelada-2.jpg",
"http://imguol.com/c/noticias/2013/12/13/13dez2013---esta-imagem-mostra-a-nebulosa-de-caranguejo-um-iconico-remanescente-de-supernova-na-nossa-galaxia-vista-do-observatorio-espacial-herschel-e-do-telescopio-hubble-uma-nuvem-de-gas-e-poeira-1386961235961_956x500.jpg",
"http://wallpaper.ultradownloads.com.br/121350_Papel-de-Parede-Imagem-Abstrata_1920x1200.jpg"
]
var currentDiv = "div2";
var count = 0;
var lenght = colors.length;
var timeForNextImage = 0;
var preloadOk = false;
setInterval(function() {
count ++;
if (count > lenght) count = 0;
var date = new Date();
var time = date.getTime();
if (time > (timeForNextImage - 3000) && preloadOk == false) {
preLoad();
} else if (time > timeForNextImage) {
play();
}
}, 300);
var play = function() {
if (currentDiv == "div2") {
$('#'+currentDiv).css("visibility", "visible");
} else {
$('#div2').css("visibility", "hidden");
}
var date = new Date();
timeForNextImage = date.getTime() + 10000;
preloadOk = false;
$("#lbl").text("div atual: "+currentDiv);
};
var preLoad = function() {
if (currentDiv == "div1") {
currentDiv = "div2";
} else {
currentDiv = "div1";
}
$("#" + currentDiv).css("background-image", 'url('+colors[count]+')');
preloadOk = true;
};
How you can look, I do a preload, in theory.. but, the browser only processes my image when I put it in the stage ?
What if I change the z-index attribute, it renders again?
You return preloadOK = true but the image doesn't load. That's not a preloader.
To make a preloader you can play with new Image() object or with load() event.
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
See more
3 Ways to Preload Images with CSS, JavaScript, or Ajax
A simple way to preload an image is to just create an image tag and set the url as the src. You don't have to attach it to the DOM to make the request.
var preLoad = function() {
var img = new Image();
img.src = colors[count];
};

Loading bar while image loads from getElementById

Below I have some code for a comic website I'm maintaining. When you click various buttons or select a page from the drop down menu the image changes to the corresponding image. However the image remains on the previous image until the new one has loaded. Is there any way I can add a loading bar or one of the spinning circle things until it has happened?
FYI, I'm not heaps advanced with JS, and this is my own code creation. Help much appreciated.
// Drop Down Menu, next and previous buttons
// Buttons
$(document).ready(function () {
var dd = $('#HailComic');
var max_len = dd.find('option').length;
$('#nextpage').click(function () {
var x = dd.find('option:selected').index();
if (max_len == x + 1) x = -1;
dd.find('option').eq(x + 1).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
});
$('#previouspage').click(function () {
var x = dd.find('option:selected').index();
if (0 == x + 1) x = max_len;
dd.find('option').eq(x - 1).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
});
$('#lastpage').click(function () {
var x = max_len;
dd.find('option').eq(x - 1).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
});
$('#firstpage').click(function () {
dd.find('option').eq(0).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_001.jpg";
});
});
// List Changing
$(document).ready(function(){
// Select
var changeHailImage = function () {
document.getElementById('hail_image').src = "images/comic/hail_" + this.options[this.selectedIndex].value + ".jpg"
}
var HailList = document.getElementById('HailComic');
HailList.addEventListener('change', changeHailImage, false);
});
You an use img.load() function to achieve this. Please check the pen http://codepen.io/anon/pen/VvwWWj
var changeHailImage = function () {
document.getElementById('hail_image').src = 'loading.gif';//get a loading image
var img = new Image();
img.src = "images/comic/hail_" + this.options[this.selectedIndex].value + ".jpg";
img.onload = function () {
document.getElementById('hail_image').src = img.src;
}
}

How to do line preloader with jquery

I tried this code for a line preloader but it didn't work and i don't know where is the problem.
var $preload = $("<div class='preloader'><div class='percent'></div><div class='line-parent'><div class='line'></div></div></div>");
$("body").prepend($preload);
var $imgs = $("img");
var imgsLoaded = 0;
var ratio = 0;
$imgs.each(function(){
$this = $(this);
$this.load(function(){
imgsLoaded++;
ratio = imgsLoaded / $imgs.length;
$(".percent").html(ratio / 0.01 + "%");
$(".line").animate({
width : ratio / 0.01 + "%"
});
}, function(){
if(ratio === 1){
$(".preloader").fadeOut();
}
});
});
I belive you want to show 100% wenn all images are loaded and do some action. First load event will not work if is atteched after image is already loaded.
I sugest to check for each img comlete and naturalWidth property every 100ms (with setInterval).
Loader = (function() {
var list, img_length, loaded, interval;
function _check_one(i) { o = list[i]; if (o.complete == true && o.naturalWidth > 0) { loaded++; delete list[i]; } };
function _procent(l, a) { console.log((100*loaded/img_length) + '%'); }
function _check_list() { for(var i in list) {_check_one(i)};_procent();_kill(); };
function _kill() { if(img_length <= loaded) clearInterval(interval); }
function _start() { loaded = 0; list = $('img'); img_length = list.length;
if(img_length != loaded) interval = setInterval(_check_list, 100); }
return { start: _start }
})();
Now at end of the body or in $(document).ready(..) you need to call Loader.start();
Or put all images source (src) in data-src attribite, attach load events and copy data-scr to src attribite. In body all relevant images looks like this:
<img data-src="some url">...
In Script Tag:
$('img').on('load', function() {
// Your action.
}).each(function() { var img = $(this); img.attr('src', img.attr('data-src')); });

Javascript - loading images

I have a javascript which uses many images, and I want to load them all before the user starts clicking around. The images are a little bit big, so it takes a while. Here's my code:
startTest();
function preloadImages() {
console.log("preload images");
for(var i = 1; i <= 132; i++) {
var img = new Image();
images[i-1] = "images/"+i+".png";
img.src = images[i-1];
if(i == 132) {
img.load = doneLoading();
}
}
}
function doneLoading() {
console.log("done loading");
document.getElementById("laading").style.display = "none";
console.log("loading gone");
showReady();
}
function startTest() {
console.log("start test");
trialCount = 0;
document.getElementById("laading").style.display = "block";
preloadImages();
var hammertime = Hammer(document.body).on("touch", function(event) {
registerTouch(event);
});
startTestTime = +new Date();
console.log("end start test");
}
As you can see, startTest() is first called, which calls preload images. Here's the issue:
When I load the page in the browser, the javascript console indicates that "done loading" has been printed, however the spinny wheel on the tab in the browser shows that the webpage is still loading...
What's going on here? How can I figure out once all my images are done loading?
You need to check on each image load that the image is the last one to load. Check using a count variable (loaded).
function preloadImages() {
var loaded = 0;
for(var i = 0; i <= 132; i++) {
var img = new Image();
images.push("images/"+(i+1)+".png");
img.src = images[i];
img.onload = function(){
loaded++;
if(!(loaded < 132)){
// all images have loaded
doneLoading();
}
}
}
}
In order to do a pre-loading, you will have to keep checking the complete status for each image that is being downloaded. Since, you can't know beforehand how much time it will take for each image to download (depending on latency or size), you will have to implement a timer which will keep polling the complete status on each image.
Here is one possible algorithm:
var timer = null,
numImages = 132,
allImages = new Array;
function preLoadImages() {
document.getElementById('loadcaption').innerHTML = 'Loading images... ';
for (var i = 0; i < numImages; i++) {
var tmp = "images/" + i + ".png";
allImages[i] = new Image();
allImages[i].onLoad = imgOnLoad(tmp);
allImages[i].src = tmp;
}
timer = window.setInterval('checkLoadComplete()', 250);
}
function imgOnLoad(imgName) { window.status = 'Loading image... ' + imgName; }
function checkLoadComplete() {
for (var i = 0; i < allImages.length; i++) {
if (!allImages[i].complete) {
imgOnLoad(allImages[i].src);
document.getElementById('loadcaption').innerHTML = 'Loading images... ' + Math.round((i/allImages.length)*100,0) + ' %';
return;
}
}
window.clearInterval(timer);
document.getElementById('loadcaption').innerHTML = 'Completed.';
window.status = '';
}
Where loadcaption is a simple HTML element to show progress. (You can also use an animated gif for loading animation).
The idea is to keep checking the complete status on each image by calling checkLoadComplete by a timer. Once all images are (load) complete, the for loop exits and the timer is cleared.
You start the pre-loading process by calling preLoadImages(); function.

Script Outside of $(document).ready

I have built a site for a client and when the user clicks on a navigation link, the content of the linked page is dynamically loaded and transitioned in with JQuery, instead of loading the new page.
The problem I am having is that because it is not loading a new page, $(document).ready doesn't fire again and any JS on the individual pages gets broken. For example, if you visit http://www.woodlandexotica.com/species.php the page works correctly, but if you try to navigate to the page from http://www.woodlandexotica.com/index_dev.php, the JS won't work.
I'm not an expert in JS and I really appreciate any and all help!
The problem is that when you call ".load()", you're using a URL string and a selector suffix to extract from the loaded content. When you use ".load()" that way, jQuery strips out all the scripts and does not run them. There's nothing you can do about that other than to implement your own version of ".load()" yourself, or (better) have the other pages you load not be complete HTML pages. If you use ".load()" without the selector suffix on the URL string, then jQuery does run the scripts.
See jQuery bug 6307 for more. The bug will not be fixed but hopefully the documentation will be improved.
The way you organized this code is wrong
Keep only binding's inside document.ready and move the logic outside to a functions..which can be accessed by any page.
$(document).ready(function() {
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// CONTENT BG SLIDESHOW
//////////////////////////////////////////////////
var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];
var slideshowSpeed = 8000;
var interval;
var activeContainer = 1;
var currentImg = 0;
var navigate = function(direction) {
currentImg++;
if(currentImg == photos.length + 1) {
currentImg = 1;
}
// Check which container we need to use
var currentContainer = activeContainer;
if(activeContainer == 1) {
activeContainer = 2;
} else {
activeContainer = 1;
}
showImage(photos[currentImg - 1], currentContainer, activeContainer);
};
var currentZindex = 1;
var showImage = function(photoObject, currentContainer, activeContainer) {
// Make sure the new container is always on the background
currentZindex--;
// Set the background image of the new active container
$("#bgimg" + activeContainer).css({
"background-image" : "url(" + photoObject + ")",
"display" : "block",
"z-index" : currentZindex
});
// Fade out the current container
// and display the header text when animation is complete
$("#bgimg" + currentContainer).fadeOut(function() {
setTimeout(function() {
animating = false;
}, 500);
});
$("#bgimg" + currentContainer).css({
"z-index" : "1"
});
currentZindex = 1;
};
function photoLoaded() {
if(!--numPhotosLeft) {
navigate("next");
interval = setInterval(function() {
navigate("next");
}, slideshowSpeed);
$('#bg_load').fadeOut('fast');
$('#page_bg').animate({opacity: 1, marginLeft: '-=860'}, 500);
}
}
var photos = ["images/bg01.jpg", "images/bg02.jpg", "images/bg03.jpg"];
var numPhotosLeft = photos.length;
for(var i = 0; i < photos.length; ++i) {
var img = new Image();
img.onload = photoLoaded;
img.src = photos[i];
}
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// PAGE TRANSITION
//////////////////////////////////////////////////
// ADJUST FOR DEEPLINKING
var hash = window.location.hash.substr(1);
var href = $('a.link').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php #page_bg';
$('#page_bg').load(toLoad)
}
});
$('a.link').click(function() {
var toLoad = $(this).attr('href')+' #page_bg';
$('#page_bg').animate({opacity: 0.25, marginLeft: '-=875'}, 500, loadContent);
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4); //MODIFY FOR DEEP LINKING
function loadContent() {
$('#page_wrap').prepend('<span id="load">LOADING...</span>');
$('#load').fadeIn('fast');
$('#page_bg').css('marginLeft', 860);
$('#page_bg').css('backgroundImage', 'none');
$('#page_bg').load(toLoad,'',hideLoader);
}
function hideLoader() {
$('#load').fadeOut('fast', showNewContent);
}
function showNewContent() {
$('#page_bg').animate({opacity: 1, marginLeft: '-=860'}, 500);
}
return false;
});
//set initial position and opacity
$('#page_bg').css('marginLeft', 860);
$('#page_bg').css('opacity', 0.25);
$('#page_wrap').prepend('<span id="bg_load">LOADING...</span>');
$('#bg_load').fadeIn('fast');
//////////////////////////////////////////////////
//////////////////////////////////////////////////
});

Categories

Resources