I am developing one image gallery website, which may have thousands of photos in future. All the images comes from other Website / API or user uploads.
User uploaded images
<img src="../images/example.jpg" alt="" />
External Images
<img src="http://example.com/xyz.jpg" alt="" />
Let say, image deleted from external website. Is there a way to check photo exists from client side using jQuery / JavaScript etc?
What I think is
i) I hotlink the image from external website
ii) Image deleted from external website, when website first load, jquery will send me the dead link info to server using ajax etc
iii) I will fix the link.
Thanks in advance...
You could use the "onerror" event on your external images and create a server side script to handle the error and return a generic "image not found" image while you fix the issue.
Something like ...
onerror="this.src='/fiximage.php?q='+this.src;"
You could do something like this...
$(function() {
$(document).on("error", "img", function() {
// do something with $(this) here
});
});
That would detect broken images and allow you to do something about it.
You can use onerror event in this case.
var imgs = document.getElementsByTagName("img"),
img, i = 0;
while (img = imgs[i++]) {
img.onerror = function() {
// just an example for error reporting
Ajax.send("POST /image_error.php", {src:img.src});
// change img src
img.src = "images/error.jpg";
};
}
Related
I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}
I build a website and i want to ask the user when each time visit the site, if he want to display images or not. and if not, i want to do not load them and display the page without any img tag
i tried this, but this is not useful because the page will be loaded
function load_img () {
if (!confirm("Do you want to load the images on your site?")) {
var images = document.getElementsByTagName("img");
var l = images.length;
for (var i=0; i<l; i++) {
images[0].parentNode.removeChild(images[0]);
}
}
}
i need some code that don't load any img tag when the page load,
and not a code that hide or remove the images after the page is loaded and the images are displayed
can someone help me please with this javascript code
thank you
You can take a look at lazyload plugin for jQuery. What this plugin does is load the image when the image is on the visible area of the page.
Their idea is to put the original URL to the image in data-original attribute and in the src attribute put some small image e.g. 1x1 transparent gif like this:
<img data-original=“img/example.jpg” src=“img/grey.gif” />
and then you are able to load all the images whenever you want to just by replacing the the src.
this is a simple javascript code that you can try:
window.onload = function() {
if( confirm('Images?') ) {
var img = document.getElementsByTagName('img');
for(i in img) {
var original = img[i].getAttribute('data-original');
if( original.length ) {
img[i].setAttribute('src', original);
}
}
}
}
You could try jquery : $("img").remove();
It would be better to solve this problem from the server side!
Make start page with a link to a version of the page with images and one without the images. You can write a server side script (PHP?) to show or hide the images. Simple removing the images could break the page design. Also removing html image tags does not do the trick. What about background images, some in css files, ...
If you like to do this an on the client side with javascript you have to remove all images and add them manually with javascript.
Using jQuery you can do:
if (confirm('Hide images?'))
{
$('img').remove();
}
Without jQuery you have to use getElemtentsByTag and a loop.
I have a web page where lots of images called from server using image
scr attribute.
I have created a function like which is triggered by td click.
function GoToStep(stepNo) {
var imgSrc = $("#h1" + stepNo).val();
$(".img_vertical").css("background-image", "url(" + imgSrc + ")");
}
Now the problem is this. For slower connections the images come after some
moment.
Can I pre load images to avoid waiting time when user clicks
td?
I have seen some jquery function to pre load images.
Kindly give some idea how can I achieve it.
Pre-loading an image is equivalent to loading an image but never displaying it. So, you can easily do it like this:
<img src="image.png" alt="" style="display:none;"/>
Now this image will be loaded as soon as the html starts rendering. Whenever you need to use this image as a display or background, just set the address to image.png and it will automatically be fetched from browser's cache.
This can be done using some javascript functions. Quoting from another question.
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Explanation of how javascript preloaders work (different question)
[...] The way it works is simply by creating a new Image object and setting
the src of it, the browser is going to go grab the image. We're not
adding this particular image to the browser, but when the time comes
to show the image in the page via whatever method we have setup, the
browser will already have it in its cache and will not go fetch it
again. [...]
So in your case, you should use something like
$(function() {
// Do stuff when DOM is ready
preload([
'img/bg1.jpg',
'img/bg2.jpg',
'img/bg3.jpg'
]);
});
I have an image on a webpage which is being dynamically generated by a server-side CGI program. Periodically this image is refreshed by a timer and/or changed based on user input. So I have a JavaScript function like
// <img id="screen" src=""> is elsewhere in the page
function reloadImage() {
$("#screen").attr("src", make_cgi_url_based_on_form_inputs());
}
This works just fine, but sometimes it takes awhile to load the image. So I'd like for some sort of message to appear that says "Loading image..." but then have that image disappear when the image has loaded and is being displayed in the browser.
Is there any kind of JavaScript event that can do this? Alternatively, is there any other way I can load/change/update an image and detect when the loading is finished, through Ajax or whatever else?
You can try out this jquery solution: http://jqueryfordesigners.com/image-loading/
$(function () {
var img = new Image();
$(img).load(function () {
//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
$(this).hide();
$('#loader').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
}).attr('src', 'http://farm3.static.flickr.com/2405/2238919394_4c9b5aa921_o.jpg');
});
To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.
I've tried a number of javascript approaches, but I always run into security errors.
I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)
Has anyone done this in a simple, reusable way?
P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?
No need for fancy stuff. All you need is the createObjectURL function, which creates a URL that can be used as the image src, and can come straight from a local file.
Let's say you selected a couple of images from the user's computer using a file input element (<input type="file" />). Here's how you would create previews for image files for it:
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
function myUploadOnChangeFunction() {
if(this.files.length) {
for(var i in this.files) {
var src = createObjectURL(this.files[i]);
var image = new Image();
image.src = src;
// Do whatever you want with your image, it's just like any other image
// but it displays directly from the user machine, not the server!
}
}
}
The first step is finding out the image path. JavaScript is allowed to interrogate the upload control for a filename/path, but (for reasons of security) various browsers show different things to the JS engine than they display to the user - they tend to keep the filename intact so you can at least validate its extension, but you may get c:\fake_path\ or some similarly obfuscated thing prepended to the filename. Trying this on various browsers will give you an idea as to what gets returned as a real path, and what gets faked out, and where.
The second step is displaying the image. It's possible to display local images if you know their paths, via img tags with file:// source URLs, if the user's browser allows the file:// scheme. (Firefox doesn't, by default.) So if you can get the user to tell you what the full path to the image is, you can at least try to load it.
JavaScript has no access to the local file system for security purposes, period.
Here's a jQuery + PHP script for uploading an image an previewing it.
I have only ever seen Java applets that do this, for example, the image uploading applet on Facebook. The downside to the Java approach is that the user will be prompted to trust the applet before it runs, which is a kind of annoyance, but this allows the applet to present a file browser with image previews or do more interesting things like allows the user to upload an entire directory.
You can try this approach, although it seems it doesn't work on IE.
http://saravani.wordpress.com/2012/03/14/preview-of-an-image-before-it-is-uploaded/
It's simple and fast to code.
I put the code here just in case the source dies:
Script:
<!-- Assume jQuery is loaded -->
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the HTML:
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="img_prev" src="#" alt="your image" />
</body>