JS load image on click - javascript

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>

Related

Why is this java script not working?

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.

What is alternative for onload for <a>?

I have this HTML:
<a onmouseover="coverLookout(this,0)" style="width:100%;overflow:hidden" href="#jtCr4NsVySc" class="youtube">
<img id="video_642" style="width:100%;margin-left:0;max-width:100%;visibility:visible" src="https://img.youtube.com/vi/jtCr4NsVySc/mqdefault.jpg">
<span></span>
</a>
And js:
var yt=new Array('maxresdefault.jpg','mqdefault.jpg');
var coverLookout = function(block,i){
console.log(i);
var code=$(block).attr('href').toString().substr(1);
var url = "https://img.youtube.com/vi/" + code + "/" + yt[i];
$(function($){
$.ajax({
url: "function_js.php?page=check_img",
data: {"url":url},
cache: false,
success: function(response){
console.log(response);
if(response=="200"){
$(block).find("img").attr('src',url);return;
}else{
coverLookout(block,++i);
}
}
});
});
};
How can I use coverLookout function while *a* is loading instead of onmouseover? *A* onload doesn't work because onload I can use only with *body*. But how do onload for other tags?
A onload doesn't work because onload I can use only with body. But how do onload for other tags?
No, it works for elements that have a load event. a doesn't have a load event because it never has something to load. All a content is inline. load relates to things like images and scripts and stylesheets and such, that load a separate resource.
img has a load event, if you're talking about the image inside the link loading. You have to be sure to hook the event before setting the img source (the onload attribute works), or check the complete flag on the element if hooking the event later to see if it's already done.
From the comments below, it sounds like you want to change the img's source when the link is clicked. You can do that like this:
<a onclick="document.getElementById('video_642').src = '/new/src/here.png' ...
...or as you're using jQuery, this will handle all youtube links:
$("a.youtube").click(function() {
$(this).find("img").attr("src", "/new/src/here.png");
});
But the user may not see it, because when the link is followed, the browser tears down the page right away. You can improve the chances your user will see it if you make sure it's already in cache, by putting it on your page somewhere but hidden:
<img style="display: none" src="/new/src/here.png">
...so the browser has it in cache to display it before tearing down the page.
I want to while page is loading src in img will be changed by script
You mean when the page these links are on is loading? Okay. This would go in a script tag at the end of the body (just before the closing </body> element:
// Find all images within a.youtube links and change their `src`
$("a.youtube img").each(function() {
var img = $(this);
// Save current src so we can put it back later
img.attr("data-real-src", this.src);
// Set new source
this.src = "/new/src/here.png";
});
// Then when the page is done loading...
$(window).on("load", function() {
// Restore the original `src` values on the images
$("img[data-real-src]").each(function() {
var img = $(this);
img.attr("src", img.attr("data-real-src")).removeAttr("data-real-src");
});
});
onload Function works only with <body> so after document loading (under $(document).ready() function collect all a tags and call the function based on their index.
var els = document.getElementsByTagName("a");
for(var i = 0, l = els.length; i < l; i++) {
coverLookout(els[i],i);
}

Show preloader image when clicked on <a> tag?

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

Hiding an image until the document is loaded, then applying effects to it

I'm trying to find a simple, but bulletproof way of hiding an image until it's loaded, and then giving it some jQuery effects (e.g. fadeIn) but all the methods I've found seem to have some issues. For example, this solution:
<img id="photo" src="bigimage.jpg" style="display:none" />
$("#photo").load(function() {
$(this).fadeIn("slow");
});
May not trigger if the image is loaded before the DOM is ready (load() won't fire).
So I wrote the following, which only adds the URL once the image has definitely loaded...
$.fn.ImageLoad = function(url){
$image = $(this);
$("<img >").attr("src", url).load(function(){
$image.attr("src", url);
});
return $image;
};
$("#cast").ImageLoad("http://pas-wordpress-media.s3.amazonaws.com/wp-content/uploads/2013/08/Google-Office-Building-in-NYC.jpg").fadeIn("slow");
But it only runs the fadeIn("slow") once the image has been cached by the browser. The first time it loads, it just appears with no effects.
See your yourself here: http://jsfiddle.net/KKn4N/
Is there any way I can fix this?
Here is my version. Works every single time and completely cross browser.
$.fn.ImageLoad = function(url){
$this = $(this);
$this.hide().on('load', function(){
$this.fadeIn();
});
this[0].src = url;
};
The key is to
do the fade inside a callback
hide first
listen for the .load before you set the .src
DEMO
Yea, load the image first, then attach the fadeIn afterwards.
$.fn.ImageLoad = function(url){
$image = $(this);
$("<img >").attr("src", url).load(function(){
$image.attr("src", url);
});
return $image;
};
$("#cast").ImageLoad("http://www.wired.com/wiredenterprise/wp-content/uploads/2013/07/ff_googleinfrastructure_large.jpg");
$("#cast").fadeIn("slow");
Try this
<img
id="cast"
style="display:none"
src="http://pas-wordpress-media.s3.amazonaws.com/wp-content/uploads/2013/08/Google-Office-Building-in-NYC.jpg"
onload="$(document).ready(function(){$('#cast').fadeIn('slow')})"
/>
Not sure if I get it correctly - I'm assuming you mean hide all images when page loads until all images are loaded and then fade them in?
If so, then why not just set display:none on images (maybe give them a class .hidden {display:none}) and then wait for window load event (i.e. all loaded) and trigger fade on all images - they will then nicely all fade in at the same time.
$('img.hidden').fadeIn('slow');
Example:
html
<img class=hidden src=http://cdn-4.lifehack.org/wp-content/files/2013/09/javascript-logo.png></img>
css
.hidden{
display:none;
}
js
$(window).load(function(){
$('img.hidden').fadeIn('slow');
});

jQuery load() appears to get stuck/hang

I am using jQuery load() to check if an image that I'm replacing the src on is loaded. Sometimes it appears to get stuck or hang though. I have a jsFiddle link below to check out. To make the loading graphic get stuck on the page click one of the buttons twice.
http://jsfiddle.net/dmcgrew/LLMs8/3/
This "almost" replicates a problem on a site I'm currently building, but I think the issues are related. On the site I'm building this "hanging" only happens when I do the following steps:
Click Image 3 button
Click Hide button
Click Image 3 button again
The loading graphic is now stuck on the page.
Here is my JS...
$("button").not("off").bind("click", function(){
var imgPath = $(this).attr("data-image"); //grab image path from data attr
console.log(imgPath);
$(".loading").show(); //show loading gif
$("img.the_image").hide(); //hide the img
$("img.the_image").attr("src","http://farm7.staticflickr.com/"+imgPath).load(function() {
$(".loading").hide(); //hide loading gif
$("img.the_image").show(); //show the newly loaded img
});
});
$("button.off").bind("click", function(){
$("img").hide();
});
Is load() the best way to check if an image has been loaded? Is there a better way that I should replace the image and check if its loaded (maybe AJAX?).
You have two issues: First, your code attaches the load handler multiple times, which is causing funky behavior. Second, your code doesn't handle multiple clicks on the same element in a row. Try this:
http://jsfiddle.net/E3Avx/
$("button").not("off").bind("click", function () {
var imgPath = $(this).attr("data-image"); //grab image path from data attr
var newImgPath = 'http://farm7.staticflickr.com/' + imgPath;
if ($('img.the_image').attr('src') != newImgPath) {
$(".loading").show(); //show loading gif
$("img.the_image").hide(); //hide the img
$("img.the_image").attr("src", newImgPath);
}
});
$("img.the_image").load(function () {
console.log('load handler');
$(".loading").hide(); //hide loading gif
$("img.the_image").show(); //show the newly loaded img
});
$("button.off").bind("click", function () {
$("img").hide();
});
This problem seems to be related to you trying to load() the same image twice, as the src doesn't actually change I think it's causing problems.
The easiest way to deal with it is just to check if the current src matches the src that has been selected, eg:
if($('img.the_image').attr('src') != 'http://farm7.staticflickr.com/' + imgPath) { }
http://jsfiddle.net/LLMs8/7/

Categories