A simple guide to loading images from a directory and displaying them upon click

I am currently working on a function that includes multiple sub-functions to achieve different tasks. One function is intended to store the files received as input into an array called loadedimages within the parent function. Another function aims to display these files in the appropriate component using showLoadedImages. Lastly, there is a function designed to display the correct image file in the correct component, but it is not functioning properly. The other two functions seem to be working fine. My challenge lies in getting the last function to work while utilizing the loadedimages array. I am open to suggestions for altering the content stored in the array.

Below is the JavaScript code:

function imgviewer() {
    "use strict";
    var loadedimages = [];
    var lidivs = [];

    function loadimages() {
        var files = document.getElementById("images").files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
                alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
                break;
            }
            loadedimages.push(file);
        }
    }

    function showLoadedImages(elem) {
        loadimages();
        var ld = loadedimages;

        //var files = getLoadedImages(); //filelist obj
        for (var i = 0; i < ld.length; i++) {
            var file = ld[i];
            var reader = new FileReader();
            reader.onload = (function(file) {
                return function(e) {
                    // Render thumbnail.
                    var span = document.createElement(
                        'span');
                    span.innerHTML = [
                        '<img class="tile" src="',
                        e.target.result,
                        '" title="', encodeURI(
                            file.name), '">'
                    ].join('');
                    document.getElementById(elem).insertBefore(
                        span, null);
                    lidivs.push(span);
                };
            })(file);
            // Read in the image file as a data URL.
            reader.readAsDataURL(file);
        }
    }

    function showImage(index, elem) {
        var chosenFile = loadedimages[index];
        document.getElementById(elem).src = chosenFile;
    }
document.getElementById('images').addEventListener('change', function(){
    showLoadedImages("main");
    }, false);
}

And here is some HTML

<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory      name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg"   width="1200" height="832" alt=""/></div>
<div id="main"></div>

Whenever I call showLoadedImages("main"), the images are displayed in the main div. My goal is to be able to click on those images so they appear on "willchange".

Answer №1

Here is a solution that meets your request. While it addresses the main issue, there are still some other issues in your code that need attention. For example, the images are not thumbnails as intended, and loading shrunken images can be just as slow as loading the originals. Maybe I have overlooked something.

"use strict";
var loadedimages = [];
var lidivs = [];

function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
continue;
}
loadedimages.push(file);
}
    loadedimages.length || alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
}

function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;

//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img data-index="',
lidivs.length,
'" class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
span.addEventListener("click", foo );
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}

function showImage(index, elem) {
document.getElementById(elem).src = lidivs[index].children[0].src;
}

function foo(event) {
  showImage(event.target.dataset.index, "willchange");
}

function show() {
    showLoadedImages("list");
}

function init() {
document.getElementById("images").addEventListener("change", show, false);
}

document.addEventListener( "DOMContentLoaded", init, false );
<body>
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory      name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg"   width="1200" height="832" alt=""/></div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Troubleshooting the inconsistency of GraphQL resolver context functionality between Playground and the client in the official NextJS starter

Currently, I am making adjustments to my NextJS/Apollo application to enable SSG with GraphQL API routes. I have referenced this official NextJS starter example as a foundation for configuring the client. An issue arose in my application which led me to g ...

Tips for identifying HTML tags that include a specific attribute automatically

Is there a way to automatically identify an HTML tag that contains a specific attribute like data-wow-delay? This query revolves around wow.js. The goal is to have the classes wow bounce added automatically to any HTML tag that has this particular attribu ...

Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you. Here is my current situation: array1 = [{Apple: Ken, Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango ...

Guide to updating current rjs files to incorporate jQuery and json in Rails 3

Currently, in my Rails 3 application, I am using rjs to render partials in my controllers. An example of this is when saving a new item to a table, the table gets refreshed: respond_to do |format| format.js { render :update do |page| ...

Implement an event listener on an element dynamically inserted into the DOM through an AJAX request

My issue involves a set of checkboxes being dynamically added to a document using an Ajax call. <input type='checkbox' checked class='import'> <input type='checkbox' checked class='import'> <input typ ...

Node.js is being utilized to upload data to an FTP server with the help of js

I'm attempting to send a file to an FTP server using Node.js with the help of jsftp module.exports = async function() { const jsftp = require("jsftp"); console.log(__dirname) const ftp = new jsftp({ host: "host.name", ...

Is there a different method for looping in JSX besides .map()?

In my JSX code, I am attempting to display a specific value based on certain conditions. The current code snippet checks if the 'item.result' exists and has a length greater than 0. If so, it maps through the 'item.result' array and dis ...

"Null" is the value assigned to a JavaScript variable

I am encountering an issue on line 30 with the $.each(data.menu, function (). The console is indicating that "data is null". Can someone clarify what's happening? Thank you! function getFoodMenuData () { var url = 'http://localhost:88 ...

Tips for conducting performance analysis in React 16

In the React documentation, it is mentioned that react-addons-perf does not function with React 16 and suggests using Chrome's built-in tools for equivalent functionality. However, in my experience, I have not found this to be true. For example, let& ...

Starting a line series from the beginning of the y-axis on a bar chart using chart.js

We have a new request from the business regarding the implementation of chart.js. Take a look at the image below, which shows a combination of bar and line charts. The line chart contains only a few data points. https://i.sstatic.net/mCSlR.png Within th ...

"Navigate with Ease: Introducing the Twitter Bootstrap Scroll

Having trouble with the twitter bootstrap scroll spy feature as the navigation doesn't update until midway through scrolling and skips item 4 to reach the last item. Check out this example: http://jsfiddle.net/eoboite/kjvAa/38/ What am I doing wrong? ...

Enables tagging without the need to manually input tags using an Angular form

I'm working on an angular form that is used to create an object with tags: <form class="form-horizontal" ng-submit="createBeacon(beaconData)"> <div class="form-group"> <label>Tags</label> <div id="tags-list" data-curre ...

Setting the default value for Jquery AutoComplete

I have a scenario where I am using jQuery autocomplete with the following data being fed in: var data = [ { value: "AL", label: "Alabama" }, { value: "AK", label: "Alaska" }, { value: "AZ", label: "Arizona" } ]; My challenge i ...

How can you incorporate a value into a variable in PHP?

Hey there! I'm pretty new to PHP and I've been working on building a program that resembles a spreadsheet. My form consists of columns and cells, allowing users to add or delete rows using Javascript. The challenge I'm facing is automating t ...

Is there a way to replicate the functionality of Python's zip() function in JavaScript

Struggling to translate this function into JavaScript... def pascal(n): row = [1] k = [0] for x in range(max(n,0)): print(row) row=[l+r for l,r in zip(row+k,k+row)] return n>=1 I'm encountering difficulties with th ...

What is the most efficient method for retrieving an element using a data attribute with an object (JSON) value?

Imagine having the following HTML element: <div class='element' data-info='{"id":789, "value":"example"}'></div> By running this JavaScript code, you can access the object stored in the data attribute. console.log($(&apos ...

adjusting the position of a dynamic JavaScript panel

When trying to make a box slide in from the bottom instead of the top left, I encountered some issues with the code. After altering the CSS position and changing the code that adjusts the position, the sliding effect stopped working. It seems like there mi ...

Do not trigger mouseleave events when absolute positioned elements have overlapping layers

I am facing a challenge with a table that includes multiple rows that need to be editable and deletable. To achieve this, I have created a <div> containing buttons that should appear when hovering over the rows. While this setup works well, I am enco ...

String Replacement in JavaScript

Here's the scenario: I have a string var str="abc test test abc"; Is there a way to specifically replace the second occurrence of "abc" in the string using the str.replace() method? ...

Navigating through paths of assets in Ruby on Rails

Is there a way to import multiple Javascript and CSS files into my Ruby on Rails project? In my project, the JavaScript files are located in the /js directory and the CSS files are located in the /css directory, with numerous subfolders within each. I&ap ...