In reference to this post: How to display loading image while actual image is downloading
I have the following code, but for some reason I cannot get the #loader_img to hide. I would also like to add a preloader because the large image is really heavy, but I want to keep it simple if possible since I am new to javascript...
<img id="loader_img" src="img/ajax-loader.gif" alt="Loading..." />
<div class="magnifier" style="height: 584px; width: 467px; margin: 20px;">
<div class="maglens">
<img id="imgload" src="img/largeimage.jpg" />
</div>
</div>
JS:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
$("#imgload").on('load', function(){
// hide/remove the loading image
$("#loader_img").hide();
});
Any help will be much appreciated! Thank you!
The image's load event is almost certainly firing before you hook the event. Since it's already fired when you hook the event, you never see it occur.
Also, you start out hiding the image (#imgload), but you never then show it.
To ensure that you get the event, you have to hook load before setting the image's src.
Alternately, you can use the image's complete property to know if it's already been loaded:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
imageDone();
} else {
img.on('load', imageDone);
}
function imageDone() {
// hide/remove the loading image
$("#loader_img").hide();
// And show the image!
img.show();
}
You also have to ensure that the code above runs after the elements have been created. The best way to do that is to put your script tag containing the code after the elements it refers to in the HTML (usually putting it just before the closing </body> tag works well). As a second-best solution, you can use jQuery's ready function. Either way, you'll still need to handle the possibility the load event has already fired.
Here's an example:
<div id="loader_img">Loading</div>
<div class="content">
<img id="imgload" src="http://i.stack.imgur.com/rTQCa.jpg?s=512&g=1" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function() { // Avoid creating globals
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
console.log("Complete");
imageDone();
} else {
console.log("Wait for load");
img.on('load', imageDone);
}
function imageDone() {
console.log("Loaded");
// hide/remove the loading image
$("#loader_img").fadeOut();
// And show the image!
img.show();
}
})();
</script>
Hi you may use this method. jQuery.ready()I have tried on my computer and it's okay this way.
BTW, you forgot to let the "imgload" show again.
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
$("#imgload").ready(function(){
// hide/remove the loading image
$("#loader_img").hide();
$("#imgload").show(); // show the loaded img again
});
I think that the script is executed before the DOM is loaded.
Take your script and put it between:
$(function () {
//Your code here
});
This will insure that the code will run after the DOM is loaded.
Related
I need to load an image, js need to get link url and print this image on screen.
But it is not working.
What is wrong with my script? what can I do to make it work and improve it?
html
<div id=img></div>
<div id=loading></div>
<a href=http://png-5.findicons.com/files/icons/1580/devine_icons_part_2/128/my_computer.png class=postmini>Open image 1</a>
<br>
<a href=http://www.iconshock.com/img_jpg/BETA/communications/jpg/256/smile_icon.jpg class=postmini>Open image 2</a>
js
$(function() {
$(".postmini").click(function(){
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
$("#img").append(I);
});
});
https://jsfiddle.net/u6j2udzb/
and this loading div, what I need to do to make it work properly?
You are missing a lot and have a lot you don't need. I have commented out where you don't need items. In particular you don't need a loading because the image will be there before they see that. However, if you do want it still, you should be loading it underneath the image you are loading. So it gets covered by the image. I can update it with that if you'd like.
What you are missing is actual code to turn the href into an image source and you are not removing the default action of the anchor tag so it doesn't try loading a new page when clicked.
$(".postmini").click(function(event){
event.preventDefault();
var element = $(this);
var I = element.attr("href");
//$("#loading").html('loading...');
//$("#loading").ajaxComplete(function(){}).slideUp();
// remove old image if it is already there.
$("#img").empty();
// create variable holding the image src from the href link
var img = $("<img/>").attr("src", I)
$("#img").append(img);
});
https://jsfiddle.net/3g8ujLvd/
You just have to insert an img tag into your "display div" on click on the link... to load the image... (btw your syntax errors are terrible... you have to use quotes for attributes^^)
like this for example :
$('.postmini').on('click',function(){
//do something
});
Check this : https://jsfiddle.net/u6j2udzb/8/
(done quickly for example)
Hope it helps
You are not running an ajax script. ajaxComplete is only fired after an ajax script completed.
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
You should ad an ajax script and than ajaxComplete will run if you registered the ajaxComplete method.
At the moment you're just placing the text from the "href" attribute on the link into the div. You need to either create an image or use the link provided as a background.
The quickest way to see this is to change make this change:
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
// $("#img").append(I);
$("#img").html("<img src='"+I+"' />");
$('.postmini').on('click',function(e){
e.preventDefault();
$('#loading').html('<img src="'+this.href+'">').children('img').one('load',function(){$(this).parent().slideUp('slow');});
});
Noticed I used on instead of click this allows you to use this.href rather than a more lengthy $(this).attr('href'). I also used .one on a child image element to find out if the image has loaded.
But I've just realised that this is useless because you want to have a loader. Ma bad.
$('.postmini').on('click',function(e){
e.preventDefault();
//best have the loader.gif showing on default before the load is complete.
var img=$('<img class="loadedImage">');
img.src=this.href;
//img.css({display:none;});//remove this if you've enter CSS .loadedImage{display:none;}
$('#loading').append(img).slideDown('slow',function(){$(this).children('.loadedImage').one('load',function(){$(this).fadeIn('slow');$(this).siblings('img[src="loader.gif"]').hide();});});
});
This method is what you're looking for. Basically you want to click the link, stop the default action of going to the link, make a new image element and set the src, make sure it's hidden before load, add the new image element to loading, slide up parent loading, check for load and fade in :)
Try and run this simple snippet
$('#myButton').click(()=>{
let imgUrl = $('#imgUrl').val();
$.get(imgUrl)
.done(() => {
$('img').attr('src', imgUrl);
$('#imgText').text('');
})
.fail(() => {
$('#imgText').text('Image does not exist');
$('img').attr('src', '');
})
})
img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Image url: <input type="text" id="imgUrl" value="https://upload.wikimedia.org/wikipedia/commons/7/75/Woman_mechanic_working_on_engine_%28cropped%29.jpeg"><br>
<button id="myButton" type="button">click here to load image</button>
<div id="imgText"></div>
<img>
I would like all HTML link (<a href=...) tag to show an image (GIF preloader) center of the screen when clicked. Currently, I have a code that shows a loading progress bar but it only shows when that page is loaded. I want the GIF preloader to show immediately after user clicked on a link.
What code and where do I need to add?
Try this,
$(function(){
$('a').on('click',function(e){
$('<img src="image-pat/img.gif" class="image-loader"/>').appendTo('body');
// ....
// your code
// ....
if($('.image-loader').length) { // check length to remove image-loader again
$('.image-loader').remove();// use, if you want to remove the loader again
}
return true;
});
});
You have to preload the image.
To do that, either create an image element and hide the image, only show on click.
OR
You can call createElement on the document ready function and set its source like below:
var elem = document.createElement("img");
elem.setAttribute("src", "images/my_image.jpg");
Then, when you use that source elsewhere, it would show the image immediately as its already loaded by browser.
use jquery .imageloader()
<img class="img" src="image.png" />
<script>
$(function() {
$('.img').imageloader();
});
</script>
add the function to a button
Hope this helps.
Visit here for loads of examples.
.imageloader()
try this out
Problem- I am displaying some images on a page which are being served by some proxy server. In each page I am displaying 30 images ( 6 rows - 5 in each row). Here if due to overload or due to any other issue if proxy server could not able to server images( either all images or some of them) in 6 seconds then I want to replace unloaded image url with some other url using javascript so that I could display 30 images at the end.
What I tried is below.
objImg = new Image();
objImg.src = 'http://www.menucool.com/slider/prod/image-slider-4.jpg';
if(!objImg.complete)
{
alert('image not loaded');
}else{
img.src = 'http://www.menucool.com/slider/prod/image-slider-4.jpg';
}
I also tried with below code.
$('img[id^="picThumbImg_"]').each(function(){
if($(this).load()) {
//it will display loaded image id's to console
window.console.log($(this).attr('id'));
}
});
I could not use set time-out for each image because it will delay all page load.
I checked other similar question on stack-overflow but no solution worked me perfectly as I need to display multiple images.Please guide how to proceed.
You don't have to wait 6 seconds, or using TimeOut. You can check if the images are loaded or not using the onload Javascript/Jquery event. I know, it will take a little bit to dispatch the onerror event, let see:
Why don't use the load Jquery event on the window or the image itself?
$(window).load(function(){
//check each image
})
Disadvantage:
It will wait for other resources like scripts, stylesheets & flash, and not just images, which may or may not be OK to you.
If the image loads from the cache, some browsers may not fire off the event (included yours and that's why your code is not working)
Why don't use the error Jquery event on the image itself?
$('img[id^="picThumbImg_"]').error(function(){
//image loading error
})
Disadvantages:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
Note:: Error is almost the same that the load event
Improving the code!:
$('img[id^="picThumbImg_"]').one('error', function() {
// image load error
}).each(function() {
if(!this.complete) $(this).error();
});
This will avoid few things of the previous code, but you still will have to wait if it's a 404 and you're replacing it in the onerror event, that will take a little bit right?
So, what now!
You can use this awesome plugin!. Once you add the reference, you just have to use something like:
var imgLoad = imagesLoaded('#img-container');
imgLoad.on( 'always', function() {
// detect which image is broken
for ( var i = 0, len = imgLoad.images.length; i < len; i++ ) {
if(!imgLoad.images[i].isLoaded){
//changing the src
imgLoad.images[i].img.src = imgLoad.images[i].img.getAttribute("data-src2");
}
}
});
Your HTML markup should look like:
<div id="img-container">
<div class="row">
...
</div>
<div class="row">
<img src="original-path.jpg" data-src2="alternative-path.jpg">
...
</div>
<div class="row">
...
</div>
</div>
Note: You don't need jQuery in this case and this plugin is suggested by Paul Irish ;)
Give all your images a specific class. Loop through your images and use .load() to check if loaded, example below...
Detect image load
I have a mobile website with some contents and an image.
The image was initially set to [display:none]. After it is fully loaded, it changes to [display:block]. Below shows what have I done:
// Other website codes................
<div id='creative_div' style="display:none; width:100%;">
<img id='banner' src='http://www.example.com/my_image.jpg' style="width:100%;">
</div>
<script>
window.onload=function(){
if (document.getElementById("banner").complete && document.getElementById("banner").naturalWidth != 0){
loadImage();
}
if (!document.getElementById("banner").complete || document.getElementById("banner").naturalWidth == 0){
hide('creative_div');
}
}
</script>
<script>
function loadImage() {
document.getElementById("creative_div").style.display="block";
}
</script>
// Other website codes............
So in this case, the image will started to load when the page is loading, and it will be displayed once the page finished loading.
However, I would like the image to show once it is loaded, no matter the website is fully loaded or not. I've searched about this issue, but it seems Javascript have to execute after the page is fully loaded. I've also found something about "async" which is used for Javascript, so I really have no idea how it works.......
Any suggestions? Thanks all.
It is not entirely clear what problem you are trying to solve, but you can attach an onload handler to the image object itself and then when the image loads, it can make itself visible without regard to the load state of the rest of the page (e.g. even if the rest of the page is still loading).
<img id='banner' onload='showme(this)' src='http://www.example.com/my_image.jpg'
style="width:100%; display: none;">
function showme(obj) {
obj.style.display = "block";
}
Or, if you want to make the parent container visible, then it could be this:
<img id='banner' onload='showme(this)' src='http://www.example.com/my_image.jpg'
style="width:100%;">
function showme(obj) {
obj.parentNode.style.display = "block";
}
Another trick can be to show image on first page. Then load original page from that page. :)
This way the image will show as soon as it gets loaded. Then on first page's onload event u can call second page code :/
Does the IFRAME's onload event fire when the HTML has fully downloaded, or only when all dependent elements load as well? (css/js/img)
The latter: <body onload= fires only when all dependent elements (css/js/img) have been loaded as well.
If you want to run JavaScript code when the HTML has been loaded, do this at the end of your HTML:
<script>alert('HTML loaded.')</script></body></html>
Here is a relevant e-mail thread about the difference between load and ready (jQuery supports both).
The above answer (using onload event) is correct, however in certain cases this seems to misbehave. Especially when dynamically generating a print template for web-content.
I try to print certain contents of a page by creating a dynamic iframe and printing it. If it contains images i cant get it to fire when the images are loaded. It always fires too soon when the images are still loading resulting in a incomplete print:
function printElement(jqElement){
if (!$("#printframe").length){
$("body").append('<iframe id="printframe" name="printframe" style="height: 0px; width: 0px; position: absolute" />');
}
var printframe = $("#printframe")[0].contentWindow;
printframe.document.open();
printframe.document.write('<html><head></head><body onload="window.focus(); window.print()">');
printframe.document.write(jqElement[0].innerHTML);
printframe.document.write('</body></html>');
// printframe.document.body.onload = function(){
// printframe.focus();
// printframe.print();
// };
printframe.document.close();
// printframe.focus();
// printframe.print();
// printframe.document.body.onload = function()...
}
as you can see i tried out several methods to bind the onload handler... in any case it will fire too early. I know that because the browser print preview (google chrome) contains broken images. When I cancel the print and call that function again (images are now cached) the print preview is fine.
... fortunately i found a solution. not pretty but suitable. What it does that it scans the subtree for 'img' tags and checking the 'complete' state of those. if uncomplete it delays a recheck after 250ms.
function delayUntilImgComplete(element, func){
var images = element.find('img');
var complete = true;
$.each(images, function(index, image){
if (!image.complete) complete = false;
});
if (complete) func();
else setTimeout(function(){
delayUntilImgComplete(element, func);}
, 250);
}
function printElement(jqElement){
delayUntilImgComplete(jqElement, function(){
if (!$("#printframe").length){
$("body").append('<iframe id="printframe" name="printframe" style="height: 0px; width: 0px; position: absolute" />');
}
var printframe = $("#printframe")[0].contentWindow;
printframe.document.open();
printframe.document.write(jqElement[0].innerHTML);
printframe.document.close();
printframe.focus();
printframe.print();
});
}
Just when the html loads, not the dependent elements. (or so I think).
To fire when the rest of the page loads do jQuery(window).load(function(){ or window.onload not document onready.
You can also check to see if an image element is loaded and there... if image . load-- etc.