how to reduce load time of image in javascript - javascript

I am loading image on button click next and previous
here i have only 2 div which are animating on click of next and previous button with different images coming from database through json.
I am getting my functionality done but it looking fine only on localhost when I am uploading this on server it gets a blank screen between the animation due to image loading actually what happens my div has completed animation and showing next div but image are loaded properly so a blank div is shown
I want to reduce this load time or my screen will show when the image has been loaded completely how can I fix it ?
basically i want a ajax loader which will automatically get remove after loading
Here is my code
<table cellpadding="0" cellspacing="0" border="0" width="815" align="center">
<tr>
<td><div class="btnPrv2" id="btnPrv2"><</div></td>
<td>
<div class="slider">
<div class="mc3" id="mc3" ><img src="" class="ff3" /></div>
<div class="mc4" id="mc4" ><img src="" class="ff4" /></div>
</div>
</td>
<td><div class="btnNxt2" id="btnNxt2">></div></td>
</tr>
</table>
<script>
$(function(){
$(".mc3").animate({left:"-=782px" },350);
$(".mc4").animate({left:"-=782px" },350, function(){ curwdiv = hdiv; canAnim = true});
});
</script>

One way to do it could be load the images when loading the page but keep it hide it using zindex or something like that, then you just need to put it on front and the load time should be longer for loading the page but lesser on the button action.
Could be something like this in your html:
<div class="mc3" id="mc3" style="zindex:-1;" ><img src="" class="ff3" /></div>
And then something like this in your js to show the image (maybe in your function):
$(".mc3").zIndex(inherit);
PD: I think you should look into your ortography and sintax, it is nearly impossible to understand you question.

I've got this plug somewhere,
For example you have
<img class="preload_image" src="#">
<img class="preload_image" src="#">
<img class="preload_image" src="#">
It will count the images, and will check if all of them are already loaded, check the code below.
// .preload_image is the image class that needed to be loaded
$('.preload_image').imagemonitor({
'onLoad': function (loadedImage, totalImage) {
// While loading, progress bar will be shown
$('#load-progressbar img').css('width', Math.floor((loadedImage / totalImage) * 100) + '%');
},
'onComplete': function (loadedImage) {
// After loading, show image
$('#load-display').fadeOut(2000).queue(function () {
$('#content-display').fadeIn(2000);
$(this).dequeue();
});
}
});
Then here's the source code for that.
(function( $ ){
$.fn.imagemonitor = function(imageEvent)
{
var totalImage = 0;
var loadedImage = 0;
var loadedImageSrc = Array();
var imageObject = Array();
var isComplete = false;
var loop_delay = 200; // in miliseconds
var imgElement = this;
if(imageEvent.init == null) imageEvent.init = function(){};
if(imageEvent.onLoad == null) imageEvent.onLoad = function(){};
if(imageEvent.onComplete == null) imageEvent.onComplete = function(){};
function createImageObject()
{
imgElement.each(function(index)
{
imageObject[index] = new Image();
$(imageObject[index]).attr('src', $(this).attr('src'));
});
}
function count_loaded_image()
{
for(var i=0; imageObject[i]; i++)
{
if(!checkIfLoaded($(imageObject[i]).attr('src')))
{
if(imageObject[i].complete || imageObject[i].readyState === 4)
{
loadedImageSrc.push($(imageObject[i]).attr('src'));
loadedImage++;
imageEvent.onLoad(loadedImage, totalImage);
}
}
}
if((loadedImage == totalImage) && !isComplete)
{
isComplete = true;
imageEvent.onComplete(loadedImage);
}
else setTimeout(count_loaded_image, loop_delay);
}
function getTotalImage()
{
var tempImageSrc = Array();
imgElement.each(function(index)
{
var counted = false;
for(i=0; tempImageSrc[i]; i++)
{
if(tempImageSrc[i] == $(this).attr('src')) counted = true;
}
if(!counted) tempImageSrc.push($(this).attr('src'))
});
return tempImageSrc.length;
}
function checkIfLoaded(src)
{
var loaded = false;
for(var i=0; loadedImageSrc[i]; i++)
{
if(loadedImageSrc[i] == src) loaded = true;
}
return loaded;
}
function setOnloadEvent()
{
imgElement.each(function(index)
{
$(this).load(function()
{
if(!checkIfLoaded($(this).attr('src')))
{
loadedImage++;
loadedImageSrc.push($(this).attr('src'));
imageEvent.onLoad(loadedImage, totalImage);
if((loadedImage == totalImage) && !isComplete)
{
isComplete = true;
imageEvent.onComplete(loadedImage);
}
}
});
});
}
imageEvent.init();
totalImage = getTotalImage();
createImageObject();
setOnloadEvent();
count_loaded_image();
};
})( jQuery );

Related

how can i use two javascript slideshows on one page? html

Hi I am doing HTML the past 3 months in college and have to design a website. I am nearly done but I am trying to put 4 slideshows onto one page. I can get one working fine but the next one i create seems to overwrite the first one.. could somebody please look at my code and give me an idea what i should do.. here is my code for both slideshows except links and images are diferent.
var i = 0;
var image = new Array();
// LIST OF IMAGES
image[0] = "strawberrypancakes.jpg"
image[1] = "chickenbroth.jpg";
image[2] = "noodlesalad.jpg";
var k = image.length-1;
var caption = new Array();
// LIST OF CAPTIONS
caption[0] = "Strawberry buckwheat pancakes";
caption[1] = "Hot chicken broth";
caption[2] = "Pepper and noodle salad";
var link= new Array();
// LIST OF LINKS
link[0] = "http://www.jamieoliver.com/recipes/breakfast/";
link[1] = "http://www.jamieoliver.com/recipes/chicken/";
link[2] = "http://www.jamieoliver.com/recipes/vegetables/";
function swapImage(){
var el = document.getElementById("mydiv");
el.innerHTML=caption[i];
var img = document.getElementById("slide");
img.src= image[i];
var a = document.getElementById("link");
a.href= link[i];
if(i < k ) { i++;}
else { i = 0; }
setTimeout("swapImage()",5000);
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
swapImage();
});
<table style="border:none;background-color:transparent;">
<tr>
<td>
<a name="link" id="link" href="http://www.siteforinfotech.com/" target="_blank"><img name="slide" id="slide" alt
="my images" height="250" width="590" src="image-1.png"/></a>
</td>
</tr>
<tr>
<td align="center"style="font:small-caps bold 15px georgia; color:blue;">
<div id ="mydiv"></div>
</td>
</tr>
</table>
easiest thing, off the top of my head is to just duplicate the HTML structure for the slideshow, changing the ID and NAME attributes to link2, slide2 and mydiv2, then just duplicate the swap function, name it swapImage2() and then add it like so:
addLoadEvent(function() {
swapImage(); // for the first slideshow
swapImage2(); // for second slideshow
});
a cleaner solution would be to have a single swapimage function and pass into it the target DOM element / slideshow you want to target.
heres a quick fiddle of the quickest way I could think of Fiddle Example

Execute js after all image loaded

(I searched, but not find exactly/easy solution)
I'm trying to execute JS after all images completely loaded. My goal is, when all images finish load completely, then removeClass my-loader and addClass visible to main-slider div.
HTML:
<div class='main-slider my-loader'>
<img src="/nice-girl.jpg">
<img src="/nice-car.jpg">
<img src="/nice-boy.jpg">
</div>
Execute below js when all images completely loaded
$(".main-slider").removeClass("my-loader").addClass("visible");
Tried :
But not work, problem is it execute before complete image load:
var imagesPre = new Array;
var success = new Array;
$('.big-slides img').each(function(){
imagesPre.push(this.src);
});
for (i = 0; i < imagesPre.length; i++) {
(function(path, success) {
image = new Image();
image.onload = function() {
success.resolve();
};
image.src = path;
})(imagesPre[i], success[i] = $.Deferred());
}
$.when.apply($, success).done(function() {
$(".main-slider").removeClass("my-loader").addClass("visible");
});
Any ideia for simple solution?
You can use load() to check if the images are loaded!
$('.imgTag').each(function(){
$(this).load(function(){
$(".main-slider").removeClass("my-loader").addClass("visible");
})
})
This may not work sometimes when the images are cached by the browser. Please check Caveats of the load event when used with images
var img = $('img')
var count = 0
img.each(function(){
$(this).load(function(){
count = count + 1
if(count === img.length) {
$('.main-slider').removeClass('my-loader').addClass('visible')
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='main-slider my-loader'>
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
<img src="https://unsplash.it/200/300/?random">
</div>
But, this answer is a working case.
<div class='main-slider my-loader'>
<img class="imgTag" src="/nice-girl.jpg">
<img class="imgTag" src="/nice-car.jpg">
<img class="imgTag" src="/nice-boy.jpg">
</div>
jquery codes:
`
window.loadCount = 0;
$('.imgTag').onload(function(){
window.loadCount++;
if(window.loadCount == $('.imgTag').length){
$('.imgTag').show();
}
});
`

Add Next and Prev Buttons To Rotating Banner

I'm not knowledgeable in JS and Jquery so I'm really hoping someone here could help me out.
I want my banner to change image on page load or refresh and I found this code:
<script type="text/javascript">
window.onload = function () {
var random = document.getElementById('random');
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
random.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
The script above works pretty well(background image changes every refresh) but now I want to add a previous and next button(actually I already did) so that when viewers click on next/previous it would display another image. Is there a simple way to do this? How do I make my next and previous button work? Any help would be greatly appreciated. Thanks!
This is the only content inside the of my html:
<div id="random" style="width: 1399px; height:515px; margin:auto;">
<div id="slide_control" class="clearfix">
<span id="prev"><img alt="" title="" src="images/icn_nav-arrow2.png" /></span>
<span id="next"><img alt="" title="" src="images/icn_nav-arrow.png" /></span>
</div>
</div>
It's the #random div that changes background image on refresh as of now and I want it just like that. I added the "slide_control" which contained the "prev" and "next" button and what I want them to do is to also change the background-image of #random when they're clicked.
Most JS/JQquery slider and plugins comes with buttons and controllers but they auto-play images and if I disable the autoplay, they don't change banner/background on refresh.
I only want the images/background to randomly change on refresh or change when prev/next buttons are clicked but I don't know how to achieve this.
Here's a basic example of what you are asking for:
<script type="text/javascript">
function rotateImage(idx) {
var random = document.getElementById('random');
if (document.images) {
random.style.background = 'url(' + pictures[idx] + ')';
selectedImage = idx;
}
}
function getNext() {
var nextImage = selectedImage + 1;
if (selectedImage >= numPics) {
nextImage = 0;
}
rotateImage(nextImage);
}
function getPrev() {
var prevImage = selectedImage - 1;
if (selectedImage < 0) {
selectedImage = numPics -1;
}
rotateImage(prevImage);
}
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
var selectedImage = null;
window.onload = function () {
var chosenPic = Math.floor((Math.random() * numPics));
rotateImage(chosenPic);
document.getElementById('next').onclick = getNext;
document.getElementById('prev').onclick = getPrev;
}
</script>

How do I exchange two images in a webpage (on two consecutive clicks) using jQuery?

I have two images among many that I want to swap places between. If I click on one image, then the other, the respective images should swap with each other and the rest should remain the same. I'm a beginner at this so any help or direction would be helpful.
This works also for every image:
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
JS
$(function(){
var src="";
var old;
$("img").click(function(){
if(src=="")
{
src=$(this).attr("src");
old=$(this);
}
else
{
old.attr("src",$(this).attr("src"));
$(this).attr("src",src);
src="";
}
});
});​
Another solution without any global variable.
html
<div id="images">
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
$('img').click(function(){
if($('#images img').hasClass('selected')){
var src = $(this).attr('src');
$('.selected').attr('src',src);
$(this).attr('src',$('.selected').attr('src'));
$(this).removeClass('selected');
}
else
$(this).addClass('selected');
});
Here is a different approach that swaps the actual elements rather than the src of the img, also avoids using external variables for the swap.
$('img.swap').on('click', function() {
var t = $(this);
if (t.hasClass('clicked')) {
t.removeClass('clicked');
return;
}
var clicked = $('img.swap.clicked')
if (clicked.length === 0) {
t.addClass('clicked');
return;
}
var placeHolder = $('<div id="placeholder"></div>');
clicked.before(placeHolder);
t.after(clicked);
placeHolder.before(t).remove();
clicked.removeClass('clicked');
});​
Example - http://jsfiddle.net/BxST9/3/ (using div instead of img but shouldn't make a difference)
See the example on: http://jsfiddle.net/Lvp4j/1/
var selected;
$("img").click(
function() {
if (!selected)
{
selected = this;
$(selected).addClass("selected");
}
else
{
var src1 = $(selected).attr("src");
var src2 = $(this).attr("src");
$(this).attr("src", src1);
$(selected).attr("src", src2);
$(selected).removeClass("selected");
selected = null;
}
}
);
My code adds also a selected class so you can highlight the clicked image...
try below code
html
<div>
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
(function() {
var swapArray = [];
var count=0;
$('img').click(function(){
count++;
swapArray.push($(this).attr('src'));
$(this).addClass(count);
if(count==2){
$('.1').attr('src',swapArray[1]).removeClass('1');
$('.2').attr('src',swapArray[0]).removeClass('2');
swapArray.length = 0;
count=0;
}
});
}());​
Given this HTML:
<img src="image_1.jpg" />
<img src="image_2.jpg" />
<img src="image_3.jpg" />
<img src="image_4.jpg" />
You could use the following JavaScript:
(function() {
var previous = null;
$('img').click(function() {
var current = $(this);
if (current.is(previous)) { // clicked same image twice; reset
reset_clicked();
} else if (previous != null) { // two images clicked; swap
swap_src(previous, current);
reset_clicked();
} else {
set_clicked(current);
}
});
function reset_clicked() {
previous.removeClass('clicked');
previous = null;
}
function set_clicked(img) {
img.addClass('clicked');
previous = img;
}
function swap_src(img1, img2) {
var src1 = img1.attr('src');
img1.attr('src', img2.attr('src'));
img2.attr('src', src1);
}
}());​
The 'clicked' class is added purely so you can use CSS to style clicked images. This class could also be used to identify any previously-clicked images, but I've used a JavaScript variable instead because that's quicker than a DOM lookup.
There's a demo on JSFiddle: jsfiddle.net/cvthL/2
This answer was posted as an improved version of Jitendra Pancholi's first answer and an alternative to his/her second answer.

Image-loaded-show function by javascript in mobile browser

I'am using the following javascript code to implement image-loaded-show function in mobile web browser (supporting HTML5). Image-loaded-show means that before the image is completely loaded, the width and height is 0, namely it willn't show and occupy any space.
Now the problem is that the images will not show until all the images are loaded.
What I need is that the iamge in the page is seperate, once loaded, the image show up.
Any tips on how to modify this javascript code? thanks.
<script type='text/javascript'>
var srcs = [];
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
}
var content = document.getElementById('content');
var images = content.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
srcs[i] = images[i].src;
loadImage(images[i], srcs[i],
function (cur, img, cached) {
cur.src = img.src;},
function (cur, img) {
cur.style.display = 'none';});
}
};
var loadImage = function (cur, url, callback, onerror) {
var img = new Image();
img.src = url;
img.width = '100%';
if (img.complete) {
callback && callback(cur, img, true);
return;
}
img.onload = function () {
callback && callback(cur, img, true);
return;
};
if (typeof onerror == 'function') {
img.onerror = function () {
onerror && onerror(cur, img);
}
}
};
</script>
The source code of the page is :
<body onload="doBindLinks();"><div id="content"> images and text </div></body>
P.S: Because I need to write this javascript string in C#, I replace the (") into (').
Edited:
Is the following right:
window.doBindLinks = function() {
var elems = document.getElementsByTagName('img');
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
var link = elem.getAttribute('src');
elem.setAttribute('link', link);
elem.removeAttribute('width');
elem.removeAttribute('height');
elem.removeAttribute('class');
elem.removeAttribute('style');
elem.setAttribute('display','none');
if(link.indexOf('.gif')>0)
{
elem.parentNode.removeChild(elem);
}else{
}
elem.attachEvent('onload',onImageLoaded);
}
};
window.onImageLoaded = function() {
var elem = event.srcElement;
if ( elem != null ) {
elem.setAttribute('display','block');
}
return false;
};
Besides, the css code is:
img {width: 100%; border-style:none;text-align:center;}
But the images still wouldn't show until all are loaded.
I'm not 100% sure I understand your question. Are you trying to hide the image until it is fully loaded? Are you writing the images out to the page, or are they already in the page? Here are a couple of options:
set style="display:none". Then add onload="this.style.display='';" event listener to image.
images will each show as they are loaded.
if you are able to change the c# code, then simply write all the image urls out as a list of strings into an imageload function. Then use this function to create the images and add them to the content div.
I hope this helps you. If not, please provide more context, and I will try to help farther.
Ok, I see where you are going now. You can take out all that javascript that you have written. Maybe print it out so that you can throw it in the trash. Then take my example here... and it will do the trick for you. each image shown only as it is loaded. Obviously if you want to change any other properties you can do it in the showImage function. hope this helps.
<html>
<head>
<style>
img{display:none;}
</style>
<script type="text/javascript">
function showImage(elem) {
elem.style.display = 'block';
}
</script>
</head>
<body><div id="content">
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
<img src="http://t0.gstatic.com/images?q=tbn:ANd9GcTlpi72nRCVE5cOz3AImtbb7GEbEYRVLkLJxAZsT5Z4XKicteDo" onload="showImage(this)" />
</dvi>
</body>
</html>

Categories

Resources