I'm trying to update my image source using jquery. To do it, I am calling .load
function that will return a string which in turn will be used to replace the image source.
srcResult value is new/icon.png:
<script>
var iconLinkURL = "Users/NewIcon";
var srcResult = $("#iconImage").children('img').load(iconLinkURL);
$("#iconImage").children('img').attr('src', srcResult);
</script>
HTML Side
<a id="iconImage"><img src="old/address.png"></img></a>
What happens is that when the javascript is loaded, the image is loaded like this:
<a id="iconImage"><img src="[object Object]">new/icon.png</img></a>
Am I missing something hence the issue is persisting?
load() returns an object. If you're not interested in pre-loading, just replace your code as follows:
$("#iconImage").children('img').prop('src', 'Users/NewIcon');
However, if you wish to preload the image, use the following:
var src = 'Users/NewIcon',
img = new Image();
img.src = src;
img.onload = function() {
$('#iconImage').children('img').prop('src', this.src);
};
It's worth noting that you will also need to wrap your code in the DOMReady event if you're not doing that already.
Related
I have an image that sometimes returns a 404 error. To get the image to load, it usually works if the image src is slightly modified, for example adding "?reload=true" to the end of it. How do I do this using JavaScript?
<img src="example.com/image.png" onerror="reloadImage()">
<script>
function reloadImage() {
// Set img src to "example.com/image.png?reload=true"
}
</script>
Try passing the element into the function, also clear the error event else it could infinite loop.
function reloadImage(img) {
img.onerror = null
let url = new URL(img.src)
url.searchParams.set('reload', 'true')
img.src = url.toString()
}
<img src="example.com/image.png" onerror="reloadImage(this)">
The ideal solution would be to track down why it's erroring in the first place and fix that.
I want to dynamically load the src from This Person Does Not Exist for multiple img objects on the DOM.
When using the jquery attr function, every img object contains the same image. I want each object to contain a "refreshed" image.
I have successfully managed to get it to work using setTimeout but would prefer if I didn't have to wait for them to load.
$(document).ready(function() {
var time = 0;
$('.imgDNE').each(function(e) {
time+=2000;
var obj = $(this);
window.setTimeout(function() {
$(obj).attr("src","https://thispersondoesnotexist.com/image?"+ new Date().getTime());
},time);
});
});
Try a pure JS solution using DOM attributes :
document.addEventListener("DOMContentLoaded", function() {
var myImg = document.getElementsByClass("imgDNE")
myImg[0].setAttribute("src", "https://thispersondoesnotexist.com/image#" + new Date.now());
});
Use # at the end of the URL to "fool" the browser's cache without bypassing upstream caches
You could also try this trick here, by setting the src attribute to itself :
myImg.src = myImg.src;
I have script that I would like visitors on my website to run when they load a web page. It looks like this:
window.onload = function(){
var pxl=document.createElement('img');
pxl.setAttribute('src', 'http://localhost:8080/getTrackingPixel')
document.body.appendChild(pxl);
}
Most of the times the source returns an image and it works fine. However, sometimes it returns this:
<html><body style="background-color:transparent"></body></html>
And I can't really change the fact that it might sometimes not return an image. How do I change the javascript so that it can handle the html response without any errors? It might be possible for me to predict when it happens though - but I haven't managed to find a good way to request the source and return the html either.
You can achieve it by using the javascript Image object which, unlike the createElement approach, allows you to fetch the src url before inserting the img in the DOM.
The onload event of the Image object won't fire if the loaded content isn't an img.
Here it is :
window.onload = function(){
var pxl = new Image();
pxl.onload = function(){
// is IMG
document.body.appendChild(pxl);
}
pxl.onerror = function(){
// is not IMG
// Meaning in your case : <html><body style="background-color:transparent"></body></html>
}
pxl.src = 'http://localhost:8080/getTrackingPixel';
}
(Note that your code also missed the semicolon ";" line 4)
what I need to do is simple to say but (for me) hard to do:
using javascript, given an image name, ie "image01.jpg", I need to check if this image exists in a certain folder or path (local or on the web). If the image does not exist under that folder, I need to check if the same image exists in another folder.
for example, with pseudo code
imageToFind = 'image01.jpg'
path1 = 'users/john/images'
path2 = 'users/mike/img'
if path1+'/'+imageToFind exists
//do something
else
if path2+'/'+imageToFind exists
//do something
else
print('NOT FOUND')
what kind of approach do you suggest? I tryed to achieve this using ajax first, and then using javascript's Image() , but I failed in both these cases.
Thanks in advance for any help, best regards
Use the onerror callback :
var img = new Image();
img.onerror = function(){
img = new Image(); // clean the error (depends on the browser)
img.onerror = function(){
console.log('not found at all !');
};
img.src = path2+'/'+imageToFind;
};
img.src = path1+'/'+imageToFind;
You can pretty much rely on native onload and onerror event handlers which fire for Image nodes. So it could look like
var images = ['users/john/images/image01.jpg','users/mike/img/image01.jpg','some/more/path/image01.jpg'];
(function _load( img ) {
var loadImage = new Image();
loadImage.onerror = function() {
// image could not get loaded, try next one in list
_load( images.shift() );
};
loadImage.onload = function() {
// this image was loaded successfully, do something with it
};
loadImage.src = img;
}( images.shift() ));
This code probably does a little more than you actually asked for. You can basically but as much image paths as you wish into that array, the script will search the list until it could load one image successfully.
try something like
objImg = new Image();
objImg.src = 'photo.gif';
if(!objImg.complete)
{
img.src = path2+'/'+imageToFind; //load other image
}else{
img.src = path1+'/'+imageToFind;
}
I think you need to ask yourself: why don't I know whether the images exist?
I feel like you should not have this problem, or want to solve it in this way.
I'm using the following code to insert some HTML into a div, and to preload any images that might be contained in that HTML (the html var's data is actually fetched from an AJAX request in the real code). This is to prevent the browser from loading the fetched HTML's images upon showing the div (using the slideDown event) - because this results in the effect's fluidity being broken as it loads image mid-transition. I suppose I could use an interlaced JPEG so that the dimensions of the image are known almost immediately, but obviously it'd be nice to get a cleaner method worked out. :P
var html = '<img src="images/test.jpg" alt="test" />';
$('div.content').hide().html(html);
$('div.content img').each(function(){
var img = new Image();
img.src = $(this).attr('src');
$(this).attr('src', img.src);
});
$('div.content').slideDown('normal');
I'm using the Image object and its subsequent assigning as per the advice given here, but unfortunately the image still isn't cached by the browser using this method, because the sildeDown() effect is still interrupted as the image loads.
Any help or alternative methods? Many thanks.
Edit - 21st Sept 09
Progress! Turns out the browser was caching the image, I just wasn't giving it time to do so (it just needed a second to load with an alert() or setInterval()). Now introducing what is probably the messiest code ever - I am using an infinite loop to create that pause.
The new method extends the old code above by binding a function (that adds each image's src to an array) to that image's successful load event. It then gets stuck in an infinite loop as it waits until all the images have loaded and therefore appeared in the array. This seems to work as a way to synchronously pre-load images - but a problem remains; the while() loop for some reason cycles infinitely even once all the images are loaded, unless I add an alert() to pause it for a moment.
The new code:
var html = '<img src="images/test.jpg" alt="test" />';
$('div.content').hide().html(html);
// define usr variables object
$.usrvar = {};
// array of loaded images' urls
$.usrvar.images = [];
// boolean for whether this content has images (and if we should check they are all loaded later)
$.usrvar.hasimages = false;
// foreach of any images inside the content
$('div.content img').each(function(){
// if we're here then this content has images..
$.usrvar.hasimages = true;
// set this image's src to a var
var src = $(this).attr('src');
// add this image to our images array once it has finished loading
$(this).load(function(){
$.usrvar.images.push(src);
});
// create a new image
var img = new Image();
// set our new image's src
img.src = src;
});
// avoid this code if we don't have images in the content
if ($.usrvar.hasimages != false) {
// no images are yet loaded
$.usrvar.imagesloaded = false;
// repeatedly cycle (while() loop) through all images in content (each() loop)
while ($.usrvar.imagesloaded != true) {
$('div.content img').each(function(){
// get this loop's image src
var src = $(this).attr('src');
// if this src is in our images array, it must have finished loading
if ($.usrvar.images.indexOf(src) != -1) {
// set imagesloaded to trueai
$.usrvar.imagesloaded = true;
} else {
// without the pause caused by this alert(), this loop becomes infinite?!
alert('pause');
// this image is not yet loaded, so set var to false to initiate another loop
// (ignores whether imagesloaded has been set to true by another image, because ALL
// need to be loaded
$.usrvar.imagesloaded = false;
}
});
}
}
$('div.content').slideDown('normal');
I made the following solution but it hasn't been tested, so you're warned ;)
// HTML (any formatting possible)
// no src for the images: it is provided in alt which is of the form url::actualAlt
var html = "<p><img alt='images/test.jpg::test' /><br />Some Text<br /><img alt='images/test2.jpg::test2' /></p>";
$(document).ready(function() {
// Reference to the content div (faster)
var divContent = $("div.content");
// Hide the div, put the HTML
divContent.hide().html(html);
// Webkit browsers sometimes do not parse immediately
// The setTimeout(function,1) gives them time to do so
setTimeout(function() {
// Get the images
var images = $("img",divContent);
// Find the number of images for synchronization purpose
var counter = images.length;
// Synchronizer
// will show the div when all images have been loaded
function imageLoaded() {
if (--counter<=0) $('div.content').slideDown('normal');
}
// Loading loop
// For each image in divContent
$.each(images,function() {
// Get the url & alt info from the alt attribute
var tmp = $(this).attr("alt").split("::");
// Set the alt attribute to its actual value
$(this).attr("alt",tmp[1]);
// Wire the onload & onerror handlers
this.onload = this.onerror = imageLoaded;
// Set the image src
this.src = tmp[0];
});
},1);
});
Create an interval/timeout and let it check your compterGenerated css-height, if it's autosized it'll begin from 0 and end to 100 (for example). But in Safari it loads the height before the image, so it'll propably not work in all browsers...
I was playing with this and I created a slightly different solution. Instead of pushing images onto an array when they are loaded, you push them all onto an array in the loop, then in the load event you remove them from the array and call a 'finished' function. It checks if the images array is empty, and if it is then it clears up and shows the content.
var html = '< animg src="images/test.jpg" alt="test" />'; // not allowed to post images...
$('div.content').hide().html(html);
// preload images
// define usr variables object
$.usrvar = {};
// array of loaded images' urls
$.usrvar.images = [];
// initially no images
$.usrvar.hasimages = false;
$('div.content img').each(function() {
// if we're here then this content has images..
$.usrvar.hasimages = true;
// set this image's src to a var
var src = this.src;
// add this image to our images array
$.usrvar.images.push(src);
// callback when image has finished loading
$(this).load(function(){
var index = $.usrvar.images.indexOf(src);
$.usrvar.images.splice(index,1);
finish_loading();
});
// create a new image
var img = new Image();
// set our new image's src
img.src = src;
});
if(!$.usrvar.hasimages) finish_loading();
function finish_loading() {
if($.usrvar.hasimages) {
if($.usrvar.images.length > 0) return;
}
$('div.content').slideDown('normal');
}
Edit: Looking at Julien's post, his method is better. My method works in a similar way but like the original solution keeps track of images by an array of srcs rather than just a count (which is more efficient).
Edit 2: well I thought it was a better solution, but it seems it doesnt work for me. Maybe something to do with the load event getting called too close to each other. Sometimes it will work but sometimes it will hang when loading images, and the image counter never reaches zero. I've gone back to the method in my post above.
Edit 3: It appears it was the setTimeout that was causing the problem.
This is what I use. As you can see by my points, I'm no pro, but I found this somewhere and it works great for me and seems much simpler than everything posted. Maybe I missed a requirement though. :)
var myImgs = ['images/nav/img1.png', 'images/nav/img2.png', 'images/nav/img3.png', 'images/nav/img4.png', 'images/expand.png', 'images/collapse.png'];
function preload(imgs) {
var img;
for (var i = 0, len = imgs.length; i < len; ++i) {
img = new Image();
img.src = imgs[i];
}
}
preload(myImgs);