load remote images via Javascript, then selectively add to array - javascript

Using javascript I'm trying to load images not on the current page (from an array of image links) and if they are large enough, add them to an array. I'm executing this after the current page has loaded, though a bookmarklet, or firebug console. Using FF.
The closest I've come is the below, but this does not seem to work, and I'm guessing this is because the size test is running before the images have loaded. Apparently my attempt to fix this with 'onload' does not work. How can I fix this up, or is there a better/simpler way to accomplish this task?
(function() {
//create array for the images
var imageArray = new Array();
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
//dispImage = '<img src=' + x.src + '><br>';
//document.write('<center>' + dispImage + '</center>');
}
return true;
}
//given an array of imageLinks:
for (x in imageLinks){
//create an image form link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = loadIfBig(im);
}
//view results:
for (x in imageArray){
disp_image = '<img src='+imageArray[x].src+'><br>';
document.write('<center>'+disp_image+'</center>');
}
})();
Update:
Thanks! sure you're right and I'm missing something stupid here, but I made the change you suggested, and then pulled writing the elements into loadIfBig, but it doesn't seem to be executing that function. current code below, including a couple sample input links:
(function() {
var imageArray = new Array();
var imageLinks = ['http://1.bp.blogspot.com/_mfMRTBDpgkM/SwCwu1RPphI/AAAAAAAAJpw/v9YInFBW84I/s1600/800px-San_Francisco_in_ruin_edit2.jpg','http://2.bp.blogspot.com/_mfMRTBDpgkM/SwCwulSZ_yI/AAAAAAAAJpo/NsRcJdpz4Dk/s1600/San_Francisco_PC_59.jpg']
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
dispImage = '<img src=' + x.src + '><br>';
document.write('<center>' + dispImage + '</center>');
}
return true;
}
processImages = function(){
for (x in imageLinks) {
//create an image from link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = function(){
loadIfBig(this);
}
}
}
})();

Your fix doesn't work because you're actually executing it immediately.
im.onload = loadIfBig(im) is actually running the function.
What you can do is something like:
im.onload = function() {
loadIfBig(this);
}
Another problem is the fact that you're running through the array of big images before the onload callbacks have actually executed. That needs to be stuck in a different function and called once all the onloads are done.

Related

Connect function to pictures displayed from a PC folder

I'm pretty new to JS and programming altogether so I'm sorry in advance if the explanation is a little sloppy, but I'll try to make it as clear as possible.
So what I'm trying to do is have a JS code that reads and displays (in an HTML page) photos from a PC folder, makes them clickable and on the click it redirects you to a page with the same photo but in high resolution.
Now, I have this piece of code that displays the said pictures, but the thing is I don't seem to be able to figure out how to "connect" it to the pictures and make them clickable. What makes it more difficult is that I'm trying to make all of this code dynamic (as you can see I've done in the below code), so I would like not to have any hardcoded titles of pictures and so on.
var index = 1;
var tempImg = new Image();
tempImg.onload = function(){
appendImage();
}
var tryLoadImage = function(index){
tempImg.src = 'img/' + index + '.jpg';
}
var appendImage = function(){
var img = document.createElement('img');
img.src = tempImg.src;
document.body.appendChild(img)
tryLoadImage(index++);
}
tryLoadImage(index);
Any help is very much appreciated, thank you very much!
You can make your images clickable by adding an onclick function to them. Try something like this:
var appendImage = function(){
var img = document.createElement('img');
img.src = tempImg.src;
img.onclick = e => {
// do something you want to show the full picture like this maybe
var el = document.getElementById("fullpictureid");
if (el && e.target.src) {
el.src = e.target.src;
// so that it sets "src" in <img id="fullpictureid"> for example
}
};
document.body.appendChild(img)
tryLoadImage(index++);
}

Image src relative path to absolute path

I have website and now making a hybrid app for it.
I get all my blog post using Jquery get method.
However the issue is that <img src="/media/image.png"> is sometime relative url and sometime an absolute url.
Everytime an absolute url breaks the image showing 404 error.
How to write Jquery function to find if src is absolute and change it to
https://www.example.com/media/image.png
I will not be able to provide any code samples I have tried since I am not a front end developer and tried whole day solving it.
Note: I need to change images present only in <div id="details"> div.
You should always use same path for all the images, but as of your case you can loop through images and append the domain, as of the use case I have added the domain in variable you can change it as per your requirement.
You can use common function or image onload to rerender but I h
Note: image will rerender once its loaded.
var imageDomain = "https://homepages.cae.wisc.edu/~ece533/";
//javascript solution
// window.onload = function() {
// var images = document.getElementsByTagName('img');
// for (var i = 0; i < images.length; i++) {
// if (images[i].getAttribute('src').indexOf(imageDomain) === -1) {
// images[i].src = imageDomain + images[i].getAttribute('src');
// }
// }
// }
//jquery solution
var b = 'https://www.example.com';
$('img[src^="/media/"]').each(function(e) {
var c = b + $(this).attr('src');
$(this).attr('src', c);
});
//best approach you are using get request
//assuming you are getting this respone from api
var bArray = ["https://www.example.com/media/image.png", "/media/image.png"]
var imgaesCorrected = bArray.map(a => {
if (a.indexOf(b) === -1) {
a = b+a;
}
return a;
});
console.log(imgaesCorrected);
img {
width: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/image.png">
<img src="https://www.example.com/media/image.png">
document.querySelectorAll('#details img').forEach(img => {
const src = img.getAttribute('src');
// use regex, indexOf, includes or whatever to determine you want to replace the src
if (true) {
img.setAttribute('src', 'https://www.example.com' + src);
}
});
The best would be to do this with the response html from the ajax request before inserting into the main document so as to prevent needless 404 requests made while changing the src
Without seeing how you are making your requests or what you do with the response here's a basic example using $.get()
$.get(url, function(data){
var $data = $(data);
$data.find('img[src^="/media/"]').attr('src', function(_,existing){
return 'https://www.example.com' + existing
});
$('#someContainer').append($data)'
})
You can just get all the images from an object and find/change them if they don't have absolute url.
var images = $('img');
for (var i = 0 ; i < images.length ; i++)
{
var imgSrc = images[i].attributes[0].nodeValue;
if (!imgSrc.match('^http'))
{
imgSrc = images[i].currentSrc;
console.info(imgSrc);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/test.jpg">
<img src="/media/test.jpg">
<img src="https://www.example.com/media/test.jpg">

How to get remote image using jQuery asynchronously?

I want to show a remote image on my page. I use Bootstrap 2.3.2 Carousel. All the information comes from another web site's RSS feed. I get data into a div like the following:
...
<div id="newsItem-<?php echo $i;?>" class="item" data-src="<?php echo $feed[$i]->image; ?>" data-alt="<?php echo $feed[$i]->title; ?>">
</div>
...
The images takes too long to load. Page is loaded about 15 seconds. So I have decided to load images after the page loading finished.
There could be various dimensions of the pictures to be displayed.
I want to show the largest existing one.
For each news item, all the images may have different but similar dimensions such as 1024x768, 620x350, 528x350, 527x350.
I have written a jQuery script to achieve this but something is wrong.
jQuery(function () {
jQuery("div[id^='newsItem-']").each(function () {
var r = jQuery(this).attr("data-src");
var r620 = r.replace(".jpg", "-620x350.jpg");
var r527 = r.replace(".jpg", "-527x350.jpg");
var r1024 = r.replace(".jpg", "-1024x678.jpg");
var r528 = r.replace(".jpg", "-528x350.jpg");
var altImg = jQuery(this).attr("data-alt");
if (pictureExists(r1024)){
r = r1024;
}
else if (pictureExists(r620)){
r = r620;
}
else if (pictureExists(r528)){
r = r528;
}
else if (pictureExists(r527)){
r = r527;
}
jQuery(this).prepend("<img src='" + r + "' alt='" + altImg + "' />");
jQuery(this).removeAttr("data-alt");
jQuery(this).removeAttr("data-src");
});
});
function pictureExists(url) {
var img = new Image();
img.src = url;
if (img.height !== 0) {
return false;
} else {
return true;
}
}
I want to display the largest existing picture in the carousel.
You cannot know the height/width of the image until its loaded. So its an async process.
In pictureExists function try to do it in this way:
/ Create new image
var img = new Image();
// Create var for image source
var imageSrc = "http://example.com/blah.jpg";
// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc,
// knowing that it's been loaded.
};
// Attach the source last.
// The onload function will now trigger once it's loaded.
img.src = imageSrc;
If you want to use the above way then you will have to implement promise structure to tackle the async nature of the image load to fetch the height/width
Or you can use this small plugin.
https://github.com/desandro/imagesloaded

Get images width on .load() doesn't work on all browsers except firefox

I post my question here because I haven't find an answer to my issue.
I load some image in JavaScript. Each of them are in its own div. And I want to get the width of the div.
this.biggerElmts.find('img').each(function(){
var div = $('<div/>', {'class': this.divMinPic}).appendTo(divMinPics);
var img = $('<img/>', {
'class': this.minPic,
alt:'Miniature '+$(this).attr("alt"),
src:this.urlPic($(this).attr("src"), this.minPicFolder)
}) // if image not found, we put de default file
.error(function(){console.log("error loading image");$(this).attr("src", this.minPicFolder + this.defaultMinPic);})
.load(function(){
console.info($(this).width());
})
.appendTo(div);});
My problem is that it works fine on Firefox, but it doesn't on all other browser.
Firefox return me 185 and each other return me 0.
If you had a jsfiddle of your code we may be able to look more specifically at what is happening. But to the best if my knowledge the onload event works fine in all browsers that I have tried, whether using pure javascript or jquery.
Here is another thread where jquery was used to do just what you are asking about.
I also have a couple of pure javascript demos on jsfiddle you can look at if you are interested.
Ok SO, here is some code to go with the links to jsfiddle
var display = document.getElementById("display"),
images = {
"F12berlinetta": "http://www.ferrari.com/Site_Collection_Image_115x55/f12_thumb_home_115x55.png",
"458 Spider": "http://www.ferrari.com/Site_Collection_Image_115x55/110823_458_spider_menu.png",
"FF": "http://www.ferrari.com/Site_Collection_Image_115x55/ff_thumb_home_115x55.png",
"458 Italia": "http://www.ferrari.com/Site_Collection_Image_115x55/458_italia_menu_1_dx_ok.png",
"Ferrari California": "http://www.ferrari.com/Site_Collection_Image_115x55/california_menu_3_sx.png"
},
keys = Object.keys(images),
loaded = 0,
menuWidth = 0,
noWaitWidth = 0;
function clickedIt(evt) {
alert("You chose the " + evt.target.title);
}
function onLoaded(evt) {
loaded += 1;
menuWidth += evt.target.offsetWidth;
evt.target.addEventListener("click", clickedIt, false);
if (loaded === keys.length) {
console.log("Waited load width", menuWidth);
}
}
keys.forEach(function (key, index) {
var newDiv = document.createElement("div"),
newImg = document.createElement("img");
newImg.id = "thumb" + index;
newImg.src = images[key];
noWaitWidth += newImg.offsetWidth;
newImg.title = key;
newImg.addEventListener("load", onLoaded, false);
newDiv.appendChild(newImg);
display.appendChild(newDiv);
});
console.log("Didn't wait load width", noWaitWidth);
Demo 1
Demo 2

Preloading images in an array (and waiting until they have downloaded)

So I came across another problem.
When I started redoing the webpage I am working on , I came across an idea - Why not have the page preload the materials, and while it's doing just that, show a loading screen?
Well, I made a function for that, but the thing is, it starts doing what it's supposed to, until it comes to the open() part of the image preloading. It simply does not work. It is because I am giving it the arguments[i] part that is causing it to stop there? Is there a better way to do it?
function mainPageLoad() {
var loadScreen = document.getElementById('pageload');
loadScreen.innerHTML = "<p>Loading<span id='loadingWhat'>...</span></p><img src='images/loading.gif?v2'>";
var loadspan = document.getElementById('loadingWhat');
loadspan.innerHTML = " images";
preloadImages(["images/logo.jpg"])
//loadspan.innerHTML = " content";
//preloadContent([""]);
}
function preloadImages() {
var images = new Array();
var imagesToLoad = arguments.length;
document.writeln(imagesToLoad);
var imagesLoaded = 0;
document.writeln(imagesLoaded);
for (i = 0; i < arguments.length; i++) {
document.writeln("Loading images.");
images[i] = new XMLHttpRequest();
document.writeln("Made object");
images[i].open("GET", arguments[i], true);
document.writeln("Well, that worked.");
images[i].send(null);
document.writeln("Sent.");
images[i].onreadystatechange = function() {
document.writeln("Ready state change!");
if (images[i].readystate == 4 && images[i].status == 200){
imagesLoaded = imagesLoaded + 1;
window.alertln("We have loaded another image.");
window.alertln("Image" + String(imagesLoaded) + "out of" + String(imagesToLoad));
}
}
}
}
window.onload = init;
Here's a much, much simpler way to preload images and have it call a callback when the images are done loading in a related prior question/answer: Image preloader javascript that supports events.

Categories