/    Sign up×
Community /Pin to ProfileBookmark

loading images using JS

My current JS loads images on a page that are locally stored (below),

**I want them to load in the webpage from a .txt file instead.**

JS

[code]
var xhr = new XMLHttpRequest();
xhr.open(“GET”, “files/img”, true);
xhr.responseType = ‘document’;
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName(“a”);
for (x of elements) {
if ( x.href.match(/.(jpe?g|png|gif)$/) ) {
let img = document.createElement(“img”);
img.setAttribute(“id”, “galleryImg”);
img.classList.add(“w-100”)
img.classList.add(“container”)
img.src = x.href;
document.body.appendChild(img);
}

};
}
else {
alert(‘Request failed. Returned status of ‘ + xhr.status);
}
}
xhr.send()
[/code]

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumFeb 27.2020 — Does that txt file contain the file names of the images?
Copy linkTweet thisAlerts:
@wprauthorFeb 27.2020 — @Sempervivum#1615361 oops... no, it contains the direct image urls.
Copy linkTweet thisAlerts:
@SempervivumFeb 27.2020 — @wpr#1615364 Then things are much easier. Try this code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "imagelist.txt", true);
xhr.responseType = 'text';
xhr.onload = () => {
if (xhr.status === 200) {
const imgsrcs = xhr.response.split('n');
imgsrcs.forEach(item => {
let img = document.createElement("img");
// img.setAttribute("id", "galleryImg");
img.classList.add("w-100")
img.classList.add("container")
img.src = item;
document.body.appendChild(img);
});
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()

Remarks:
  • 1. An ID has to be unique, therefore I deactivated it in the code above.

  • 2. I assumed that the image urls are separated by newlines. Unfortunately the newline is platform dependent. I recommend using commas or semicolons as a separator.

  • 3. IMO the fetch API is more easy to handle and more clear. Using it the code would read:
    fetch('imagelist.txt')
    .then((response) => {
    return response.text();
    }).then((text) => {
    const imgsrcs = text.split('n');
    imgsrcs.forEach(item => {
    let img = document.createElement("img");
    // img.setAttribute("id", "galleryImg");
    img.classList.add("w-100")
    img.classList.add("container")
    img.src = item;
    document.body.appendChild(img);
    });
    }).catch((error) => {
    console.error('Error:', error);
    });
  • Copy linkTweet thisAlerts:
    @SempervivumFeb 27.2020 — BTW: Is this thread resolved?

    https://www.webdeveloper.com/d/388497-button-onclick-requires-double-click-when-it-should-be-single-click/3
    Copy linkTweet thisAlerts:
    @wprauthorFeb 28.2020 — @Sempervivum#1615367

    thank you! hopefully this isn't too much to ask but, how would I:
  • 1. put the container around the images instead of for each image? (similarly, the images are placed after all of the scripts because that's where the script tag is? i'd like them inside my container at the beginning of the page.)

  • 2. append a line break to the final image / each?

  • 3. randomize which images load?


  • @Sempervivum#1615370

    yes. It changed from double click to single click once I made the images visible by default.
    Copy linkTweet thisAlerts:
    @SempervivumFeb 28.2020 — 
  • 1. You can add the images to your container instead of body

  • 2. I recommend using flex layout for controlling the arrangement of the images:

    https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    Use `flex-direction: row:</C> (default) to arrange them side by side.<br/>
    Use <C>
    flex-direction: column:`
    to arrange them one below the other.

  • 3. Unfortunately there is no built-in shuffling or randomizing function in javascript. The function in the code below was posted here:

    https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array


  • &lt;div id="container-id"&gt;&lt;/div&gt;
    &lt;script&gt;


    <i> </i> // shuffle an array
    <i> </i> function shuffle(a) {
    <i> </i> var j, x, i;
    <i> </i> for (i = a.length - 1; i &gt; 0; i--) {
    <i> </i> j = Math.floor(Math.random() * (i + 1));
    <i> </i> x = a[i];
    <i> </i> a[i] = a[j];
    <i> </i> a[j] = x;
    <i> </i> }
    <i> </i> return a;
    <i> </i> }
    <i> </i> fetch('imagelist.txt')
    <i> </i> .then((response) =&gt; {
    <i> </i> return response.text();
    <i> </i> }).then((text) =&gt; {
    <i> </i> // provide container for images
    <i> </i> const imgcontainer = document.getElementById('container-id');
    <i> </i> // split response text
    <i> </i> const imgsrcs = text.split('n');
    <i> </i> // shuffle images
    <i> </i> shuffle(imgsrcs);
    <i> </i> imgsrcs.forEach(item =&gt; {
    <i> </i> let img = document.createElement("img");
    <i> </i> // img.setAttribute("id", "galleryImg");
    <i> </i> img.classList.add("w-100")
    <i> </i> img.classList.add("container")
    <i> </i> img.src = item;
    <i> </i> // add current image to container
    <i> </i> imgcontainer.appendChild(img);
    <i> </i> });
    <i> </i> }).catch((error) =&gt; {
    <i> </i> console.error('Error:', error);
    <i> </i> });
    <i> </i>&lt;/script&gt;
    ×

    Success!

    Help @wpr spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.23,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...