Download three 1st images from a URL in background - javascript

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.

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 from images folder is not loading in mobilefirst

i am working with mobilefirst project.
I am facing an issue of not able to load an image in javascript. My image is placed inside a images folder. when i check the console is added inside the div and tool tip over that srctells Could not load the image.
jQuery('#placeher').show();
// var table = $('#mydemo1');
for (var i = 0; i < result.length; i++)
{
doc1=result[i];
if(doc1.PHOTO == "")
{
var elem = document.createElement("img");
elem.setAttribute("src","../common/images/Icon-60.png");
elem.setAttribute("height", "60");
elem.setAttribute("width", "60");
document.getElementById("placeher").appendChild(elem);
}
}
The correct path to use for the images folder is simply images/<image file name>. For example: <img src="images/thumbnail.png"/>.

I have created image tag in JavaScript, but it is not displaying image on web page

I am calling this function on add button from my PHTML. On click of add button I want to show image of selected fruit in <div>.
function moveoutid()
{
var sda = document.getElementById('availableFruits');
var len = sda.length;
var sda1 = document.getElementById('orderFruits');
for(var j=0; j<len; j++)
{
if(sda[j].selected)
{
alert(baseUrl+"/img/"+sda.options[j].value+".jpg");
var img1=document.createElement('img').src=baseUrl+"/img/"+sda.options[j].value+".jpg";
var di=document.getElementById('d');
di.appendChild(img1);
var tmp = sda.options[j].text;
var tmp1 = sda.options[j].value;
sda.remove(j);
j--;
var y=document.createElement('option');
y.text=tmp1;
try
{
sda1.add(y,null);
}
catch(ex)
{
sda1.add(y);
}
}
}
}
In this code I have created <img> tag and passing image path to src, to show selected image on web page. It is correctly taking path of images but it is not appending <img> tag and not displaying image on web page.
Your problem is, most likely, in this line:
var img1=document.createElement('img').src=baseUrl+"/img/"+sda.options[j].value+".jpg";
This creates an element, assigns the src property to it and then assigns the value of this src property to variable img1. Instead, you should do this in two lines:
var img1 = document.createElement('img');
img1.src = baseUrl+"/img/"+sda.options[j].value+".jpg";

How to populate alt fields with the src of an image for all images on page

I am working on a site that has a page that will have a couple hundred thumbnails. I would like to have the filenames (the src) of the images populate the alt fields. So for example, I currently have the thumbnails as follows:
<img src="images/thumb1.jpg" />
I would like to populate the alt fields with the filename. So, the desired result would be:
<img src="images/thumb1.jpg" alt="thumb1" />
Is there a way I can automatically generate these alt tags using the images src?
Any suggestions are appreciated. Thank you for the help!
An untested, first guess, would be:
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
images[i].alt = images[i].src;
}
JS Fiddle demo.
Just to demonstrate how much easier this can be, with a JavaScript library, I thought I'd also offer the jQuery demo too:
$('img').each(
function(){
this.alt = this.src;
this.title = this.src;
});
jQuery-based JS Fiddle demo.
Edited because I'm an idiot...
I forgot to point out that you'll need to wait for the window to finish loading (or, at least, for the document.ready event), so try it this way:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i = 0; i < numImages; i++) {
images[i].alt = images[i].src;
images[i].title = images[i].src;
}
}
And change the opening body tag to:
<body onload="makeAlt">
JS Fiddle demo.
Edited to address the OP's final question:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
var newAlt, stopAt;
for (i = 0; i < numImages; i++) {
newAlt = images[i].src.split('/').pop();
stopAt = newAlt.indexOf('.');
newAlt = newAlt.substring(0,stopAt);
images[i].alt = newAlt;
images[i].title = newAlt;
}
}
JS Fiddle, though I suspect there's a far more concise way...
To get the file name you could add to David Thomas's code...
var name = images[i].getAttribute('alt').split('/');
name = name[name.length-1].split('.')[0];
So that you end up with...
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
var name = images[i].getAttribute('src').split('/');
name = name[name.length-1].split('.')[0];
images[i].setAttribute('alt') = name;
}
(Also amazingly untested)
Here it is, with some simple DOM operations and a dash of regex magic:
var imgs = document.getElementsByTagName('img');
// This will extract the file name (minus extension) from the image's `src`
// attribute. For example: "images/thumb1.jpg" => "thumb1"
var name_regexp = /([^/]+)\.[\w]{2,4}$/i;
var matches;
for ( i = 0; i < imgs.length; i++ ) {
matches = imgs[i].src.match(name_regexp);
if ( matches.length > 1 ) {
imgs[i].alt = matches[1];
imgs[i].title = matches[1];
}
}
See JSFiddle for a demo.
var images = document.getElementsByTagName("img");
var count = images.length;
for (i=0; i<count; i++){
var src = images[i].getAttribute("src");
var path = src.split("/");
var fullname = path[path.length - 1];
var name = fullname.split(".");
var result = name[0];
images[i].setAttribute("alt") = result;
}
I think the real questions you should be asking is will all this actually help my SEO, because I assume that is the reason why you would like your alt tags populated?
There is some evidence that Google is getting better at reading Javascript, but will it run the scrip before it crawls the pages and add the alt text then index the page with that alt text and consider that alt text to provide additional value outside of the keywords it already found in your file names, especially considering that it rendered the script so it will probably know that the alt is just being copied form the file name. Or will Google simply index all the html and not even bother trying to run the javascript?
I would be interested to hear any additional insight others may have on this.
I personally feel there is a low probably that this will end up helping your SEO. If you are using a content management system you should probably be looking at how to add alt text via PHP by taking the variable for the page heading or title and inserting that to the alt text.
Unless you don't care about your SEO and are really doing this for text readers, then forget everything i just said.

Image animation keeps requesting the images

I test the code in IE7, FF, Chrome, Safari and this problem occurs in Firefox only.
I have checked that the problem only occurs in FF 3.5.x, but not FF 3.0.x.
I want to make an image animation which has 10 images in total.
Currently, I use the following code to do it:
for (var i=1;i<=10;i++){
img[i] = new Image();
img[i].src = "images/survey/share_f"+i+".jpg"
}
var cornerno = 0;
function imganimate(){
$("#surveyicon").attr("src",img[cornerno].src);
//some logic to change the cornerno
setTimeout("imganimate()",1000);
}
And then change an element's src to loop through the array "img".
however, firefox keeps requesting the images continuous (I expect it only requests each unique image just once).
What should I do?
img is undefined. just add a line "var img = new Array();" before "for (var i=1;i<=10;i++){"
var img = new Array();
for (var i=1;i<=10;i++){
img[i] = new Image();
img[i].src = "images/survey/share_f"+i+".jpg";
}
var cornerno = 0;
function imganimate(){
cornerno %= 10;
cornerno++;
$("#surveyicon").attr("src",img[cornerno].src);
setTimeout("imganimate()",1000);
}
imganimate();
Try composing the images into a single image file like a sprite map and then use CSS positioning to shift the image around as a background image. It will be much faster and avoid any reloads.
You've already created ten DOM nodes, set their src and loaded the images. Why would you set the src again? You want to rotate those ten nodes in and out now. You can either toggle style.display or remove and insert the nodes.
Here's my suggestion. I'm not well versed in JQuery so there may be a few additional shortcuts I've overlooked:
var imgAmt = 10;
img = [];
for (var i=1;i<=imgAmt;i++){
img[i] = document.createElement("img");
img[i].src = "images/survey/share_f"+i+".jpg"
img[i].style.display = "none";
$("#surveyicon").appendChild(img[i]);
}
imganimate();
var cornerno = 0;
function imganimate(){
cornerno++;
cornerno = cornerno > imgAmt ? 1 : cornerno;
for (var i=1;i<=imgAmt;i++){
// hide all images but the index that matches cornerno:
img[i].style.display = i==cornerno ? "" : "none";
}
setTimeout(imganimate,1000);
}
This seems a bug in FF3.5.x.
Not sure whether the bug has already been fixed.

Categories

Resources