How to set error image for all images on page? - javascript

I would like to show my own error image when an image cant load successfully.
I thought of a JavaScript function:
<script type="text/javascript">
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].onerror = onErrorImage(images[i]);
}
function onErrorImage(element){
element.onerror = null;
element.src = 'errorImage.png';
}
</script>
But this doesn't work. This turns every image on the page into my own error image.
Is there another simple way to show my own error image on error?
Or is there another way to bind a function to an event like i did on line 4? Because I'm pretty sure the script fails on that line.
Solution may be in jQuery.

It should be i guess:
images[i].onerror = function(){onErrorImage(this);}

There are a lot of ways to do this, I will show you one of them :
You can make all of your images with "fake-src" and load them when the document is ready. Of course you can make a loader till they are downloading.
Here is a function I write for you:
imagesReady = function () {
var myImgs = document.getElementsByTagName("img");
for (var i = 0; i < myImgs.length; i++) {
getImageReady(myImgs[i]);
};
function getImageReady(el) {
var url = el.getAttribute("src-fake");
var image = document.createElement("img");
image.onload = function() {
el.src = url;
el.style.opacity = 1;
//this image is ok, that why we put his src to be the fake src
};
image.onerror = function (err) {
console.log("err on load :"+image.src);
el.src = url;
//this image fail!
}
image.src = url;
}
}
imagesReady();

Related

Load var n from localStorage and loop n times

I'm trying to learn JS and this is my little app.
Every time I press the "INSTANTIATE" button, it instantiates a tomatoe.png in my <div>.
When the user reloads the page, the tomatoe.png should appear as many times as they've pressed the "INSTANTIATE" button.
This is the code. For this purpose, I created a variable (i), and it increments on every button press.
I planned to save this variable into localStorage, and when the page gets reloaded, I want to call a loop function that instantiates the tomatoe.png i times.
function popUp() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
i++;
localStorage.setItem("apples", i);
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
So, when the user reloads the page, as many tomatoes should appear as many times they've pressed the button.
I think I have to use a loop, but I don't know how.
Just get the item in localStorage and loop until it reaches 0, creating a new image each time (localStorage don't works in StackOverflow snippets here because of security reasons, but you get the point).
var i = 0;
function popUp() {
newImage();
i++;
localStorage.setItem("apples", i);
}
function newImage() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
}
var oldi = Number(localStorage.getItem("apples"));
while (oldi > 0) {
oldi--;
newImage();
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
First of all, you have to declare i outside your function (in case you haven't done it already) and give it a value of zero, if it isn't exist in the Local Storage:
let i = localStorage.getItem("apples") || 0;
Then, create a loop, that loops i times:
for(let n = 0; n < i; n++){}
And finally, just create tomatoes:
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
So, the full code should look like this:
document.addEventListener('DOMContentLoaded', function(){
function popUp() {
createTomato()
i++;
localStorage.setItem("apples", i);
}
function createTomato() {
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
}
document.getElementById("instantiate").addEventListener("click", popUp)
let i = localStorage.getItem("apples") || 0;
for (let n = 0; n < i; n++) createTomato();
})
<button id="instantiate">INSTANTIATE</button>
<div id="header"></div>
Try it on codepen.io

Image Swap on MouseOut (JavaScript, not JQ)

I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]

Image duplication after multiple file input

Have this issue here: I want to upload several images at once and show them directly afterwards in the browser. Everything is fine. However, doing this on mobile, sometimes I don't get all the images, but duplicates of another one from the file array. I have a suspicion, that this has to do with hardware limitations, since on PC everything works fine, but not on mobile.
Here is the fiddle. You can check it via mobile to see if duplicates appear.
So in result I get this on mobile. It wasn't two images in the selection, only one:
Here I have the Javascript snippet. Is there any room for improvement? Espacially onload processes are really confusing me from time to time. Is there any chance to write it better?
Javascript:
jQuery('.upload-mobile').change(function(){
jQuery('body').toggleClass( "loading" );
var imagecounter = jQuery(this)[0].files.length;
var loadcounter = 0;
for(var i = 0; i<imagecounter;i++){
for(var p = 1;p<=12;p++){
if(jQuery('#preview'+p).length<=0){
jQuery('.image-collection').prepend(jQuery('<div></div>',{id:'preview'+p,css:{'display':'inline-block'}}));
break;
};
}
var file = this.files[i];
var reader = new FileReader();
reader.onload = function(e){
for(var w = 1;w<=12;w++){
if(jQuery('#preview'+w).children().length>0) {
}
else{
var img = document.createElement("img");
img.src = e.target.result;
img.id = 'img'+w;
img.className += " img-responsive";
img.className += " border-blue";
img.className += " image-small";
img.className += " image-cover";
img.style.display='none';
document.getElementById("preview"+w).appendChild(img);
break;
}
}
loadcounter++;
if(loadcounter==imagecounter){
var count = jQuery('.image-collection').children().length;
jQuery('.image-small').delay('1500').fadeIn('3000', function(){
jQuery('#image-counter').text(count+'/12');
jQuery('body').removeClass( "loading" );
if( jQuery('#image-counter').text()=='12/12'){
jQuery('#upload-photos').fadeOut('200', function(){
jQuery('#three-cube-compact').fadeIn('200');
})
}
});
}
};
var image = reader.readAsDataURL(file);
}
});
EDIT:
I tried to use the forEach function. I didn't use the for each loops earlier, so I can not say much about the difference between foreach and for. I can't say if it works better or not, but I have seen less duplicates (maybe I didn't check to often to asume good functionality of it). It almost works, but maybe there is another way to make it work flawlessly?
Javascript:
jQuery('.upload-mobile').change(function(){
jQuery('body').toggleClass( "loading" );
var imagecounter = jQuery(this)[0].files.length;
var loadcounter = 0;
Array.from(this.files).forEach(function (image, index){
for(var p = 1;p<=12;p++){
if(jQuery('#preview'+p).length<=0){
jQuery('.image-collection').prepend(jQuery('<div></div>',{id:'preview'+p,css:{'display':'inline-block'}}));
break;
};
};
var reader = new FileReader();
reader.onload = function(e){
for(var w = 1;w<=12;w++){
if(jQuery('#preview'+w).children().length>0) {
}
else{
var img = document.createElement("img");
img.src = e.target.result;
img.id = 'img'+w;
img.className += " img-responsive";
img.className += " border-blue";
img.className += " image-small";
img.className += " image-cover";
img.style.display='none';
document.getElementById("preview"+w).appendChild(img);
break;
}
}
loadcounter++;
if(loadcounter==imagecounter){
var count = jQuery('.image-collection').children().length;
jQuery('.image-small').delay('1500').fadeIn('3000', function(){
jQuery('#image-counter').text(count+'/12');
jQuery('body').removeClass( "loading" );
if( jQuery('#image-counter').text()=='12/12'){
jQuery('#upload-photos').fadeOut('200', function(){
jQuery('#three-cube-compact').fadeIn('200');
})
}
});
}
};
var pic = reader.readAsDataURL(image);
});
});
EDIT2:
The fiddle was updated
EDIT3:
Added an image of the mobile screen. I also figured out it might has something to do with the file explorer on the mobile device. When I select using the first file explorer, I don't get the duplication bug:
However, by clicking on Browse ("Durchsuchen" on the image), I get to another file explorer. And using that one creates this "duplication bug":
Is there maybe a way to solve this or maybe to disable the Browse button?

Download three 1st images from a URL in background

I'm actually trying to find a way in a js script to downloading the three first images from a specifiq URL.
I have find this way to download img file as a new filename, but this script don't limit the imgs downloads to three:
download-data-url-file.
Why only the three images from an URL ?
Because i would like to setup later a sort of timer to repeat the downloading task.
The URL is a content feed (http://feed.500px.com/500px-best)
Basically, the img source URL is avalaible if we enter in the Inspector tool on Firefox, we can see the URL source for a give image like:
<img xmlns="http://www.w3.org/1999/xhtml" src="https://drscdn.500px.org/photo/266885357/m%3D900/v2?webp=true&sig=b5a6df5651c4248defdeee0f5b4d1ec599d87d5fa69e7673b5d64cef5a4deeb7" />
So the js script will take the first image from the website, and download the .png image as a newfilename.png (just an filename exemple), reapeat the step for a second and a third image, and stop to run.
There is an short js that i have modded for my task, i assume that i can improve it by adding an var totalImages = 3 to limiting the total img downloads..
var data = canvas.toDataURL("http://feed.500px.com/500px-best/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "Image1.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
Thank in advance.
// This code is very specific to 500PX
// I had to use itemcontent selector, as the feed was giving small icons
// as first three images.
var parents = document.getElementsByClassName("itemcontent");
var totalImages = 3;
var done = false;
var result = [];
for(var i = 0; i < parents.length && !done; i++) {
var images = parents[0].getElementsByTagName("img");
for(var j = 0; j < images.length && !done; j++) {
result.push(images[j].src);
if(result.length == totalImages)
done = true;
}
}
// The result array contains the first three images of the page.

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