JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will find a condensed version of the relevant code snippets.

<!doctype html>
    <head>
      <style>
       div#GameBoard {
         position: absolute;
         top: 66px;
         left: 53px;
         display: block;
         margin: 10px;
         padding: 10px;
         border: ridge #7CFC00 15px;
         width: 1007px;
         height: 698px;
       }

       div#Flipper {
         display: block;
         position: relative;
         background-color: #000;
       }      
     <style>

     <script lang="javascript">
       var ImgArray = [[11-16][21-26][31-36][41-46][51-56][61-66]];
       // pseudocode, where first digit represents row and second digit column number. 
       // Images in folder named accordingly like 11.png,12.png,21.png,
       // also within the array.

       function OnClickCard(path)
       {
         path || path ='C:\Users\Jamal\Desktop\codefolder\memorygame\gameimages'

         document.getElementById("Flipper").img.src = ImgArray.splice(Math.floor(Math.random() * ImgArray.length)[ImgArray];
       }
    </script>
  <body>
    <div id="GameBoard">
        <div class="Tile" id="Flipper">
            <img name ="11" src="blue-glass-tile.png" onclick="OnClickCard()"/>
        </div>

  </body>
  </head>
</html>

I aim to store the 36 images within 'C:\Users\Jamal\Desktop\codefolder\memorygame\gameimages' in an array, randomly select an index between 0-35 to change the image source in the div, and remove that index to avoid duplication.

However, the current situation yields no results. Despite clearing all errors in Firefox's developer console, nothing seems to be happening. I am unsure how to log errors or determine if an image has loaded. As I struggle with the randomizer logic, any assistance would be greatly appreciated as I strive to finish this task successfully.

Answer №1

To start, there are a few mistakes in the code snippet you provided. The #Gameboard element is missing a closing <div> tag, and it seems like the path variable is not being used at all.

Next, executing a console log statement is simple:

console.log("logging statement");

You can include this line of code within your Javascript to print messages to the browser console.

The main issue you're facing is that web browsers have limitations when it comes to interacting with system files on your computer. When you use the

<input type='file' id='file_input'/>
element, the browser handles the file selection process for security reasons.

Depending on your browser's compatibility with the File API, you may be able to implement functionality using Javascript and event binding. However, it's often simpler to host images on a server and access them via URLs in the browser. If you're working locally, consider setting up an Apache/MySQL/PHP stack and storing data within your localhost directory.

Answer №2

Here is a simple method that focuses on extracting the image src path rather than the blob content of the image. Hopefully, this will guide you in the right direction.

To achieve this, follow these steps:

  • Insert your image into your HTML page.
  • Retrieve all images in JavaScript and store them in an array called document.images.
  • Iterate through the array of images to extract only the src paths.
  • You can utilize the data array for further processing or storage.

var images = document.images,
    data = [];
for (var i = 0, len = images.length; i < len; i++) {
  data.push(images[i].src);
  console.log(data[i]);
}
// Perform actions with the extracted image paths stored in the 'data' array
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">

<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=150%C3%9710&w=150&h=200">

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

Making a REST call with values containing an apostrophe

Currently, I am utilizing REST and ajax to retrieve data from SharePoint using the URL below: https:xxxxxxxx/_vti_bin/ListData.svc/RMSD_Tasks?$orderby=IssueValue asc,StatusValue desc&$filter="+dropValue+" eq '"+secondFilterVal+"'&groupby ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

Error: The JS Exception has not been handled, as it is stating that 'undefined' is not an object when evaluating 'global.performance.now' in react-native-tvOS

I am currently working on a React-Native-tvOs app and despite following all the instructions from the react-native-tvOs GitHub page, I keep encountering an error when running the default template app. Even after running the script provided on the GitHub re ...

What is the best way to implement a user-customizable dynamic URL that incorporates API-generated content in a NextJS and React application?

Seeking assistance with implementing customizable dynamic URLs in Next.js with React. My current project involves a Next.js+React application that uses a custom server.js for routing and handling 'static' dynamic URLs. The goal now is to transiti ...

Tips for passing the id using jQuery in an AJAX request to execute a delete action

How can I remove an element from a list by clicking the delete button? I have created an ajax call for this purpose: .ajax({ type : "GET", url : 'getVenueList', success : fun ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

The jssor slider cannot be initialized when it is loaded through ajax requests

Incorporating jQuery's .load() function, my website dynamically loads the HTML code for the jssor slider. To verify the functionality of my code, I have developed a duplicate page which already includes the necessary slider code without utilizing an a ...

having trouble loading marker in react leaflet within next.js

I am facing difficulty in implementing react leaflet Marker in my next.js project. Below is the code snippet where I have included my map component: const MapSearch = dynamic(import('../../components/Map'), { ssr: false, loading: () => ( ...

Incorporating graphics into a React component

Currently exploring React JS and looking to dive into the practical side of things. Following a documentation tutorial that constructs a basic comment system. I've replicated the component structure outlined in the tutorial: PostBox PostList Pos ...

Can you help me transform this javascript code into a JSON format?

Is there a way for me to organize my data so that I have one main question with 5 choices, each associated with a vote? It's like thinking of it as a tree where the question is the root and has 5 leaves, representing the choices, and each choice furth ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

Tips for keeping images stationary while expanding on hover

Currently, I am in the process of developing my first website. My main goal is to create an image gallery that displays thumbnails of images and expands them when you hover over each one. Initially, I adjusted the sizes of the images to 100px*100px using H ...

Troubleshooting Event Tracking Problems with Brave Browser on PostHog

After successfully implementing Posthog with React and testing it on Chrome and Firefox, we encountered issues when trying to test it on Brave/Microsoft Edge Browsers. It appears that the default ad blocker feature in these browsers is causing the problem. ...

Is there a way to add text to HTML code using CKEditor?

I incorporate CKEditor into my website. When I click on a specific link, it adds some text to the editor successfully. However, when I switch to the source tab, I am unable to append this text to the existing source code. Can anyone offer guidance on h ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Stripping quotation marks from CSV information using Javascript

After performing a fetch request using JavaScript, I have converted JSON data into CSV format. datetime","open","high","low","close","volume" "2020-01-28","312.48999","318.39999","312.19000","317.69000","31027981" "2020-01-27","309.89999","311.76001","30 ...

Unable to locate element in Internet Explorer when using frame switching within Selenium

I am currently working on a project in Selenium that is specifically designed to run in Internet Explorer, but I am encountering issues locating the xpath element. Despite this setback, I managed to make progress in the test by using the switch frame func ...

The error message "Adyencheckout is not a constructor" is popping up in my

Struggling to implement the Adyen dropin payment UI in NextJS and facing issues initializing the Adyen dropin component. Attempting to dynamically import Adyen web to avoid window is not defined error, but uncertain on how to use it as a constructor after ...

What is the process for creating a symbolic link from a project's node_modules directory?

Recently, I've been learning how to build a Password Manager using React, Node.js, and MYSQL by following a tutorial. However, I encountered an issue where the file /EncryptionHandler was located outside of the src/ directory of my project. Even thoug ...

The callback function does not get invoked when using JSONP

Learning jsonP has been a challenge for me as I am relatively new to it. I have done my research by reading various articles but when trying out a simple example, the callback function fails to execute. Surprisingly, there are no errors or exceptions logge ...