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

Updating variable values in AngularJS while navigating through routes

How can I dynamically set the flag icon inside the page header based on the selected language using AngularJS? The language selection is done in a separate .htm file and all managed by AngularJS routing. My application has a single controller called "appCo ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

Object.assign versus the assignment operator (i.e. =) when working with React components

Just a quick question: I've come across some answers like this one discussing the variances between Object.assign and the assignment operator (i.e. =) and grasp all the points made such as object copying versus address assignment. I'm trying to ...

unable to retrieve data using ajax

Having some trouble with my ajax code that is supposed to print values: success: function(returndata) { $('#first').html("<div id='first' class='progress-bar progress-bar-primary' role='progressbar' aria-valu ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

Is there a way to determine the app bar height within a React Material UI application?

I'm trying to create a full-screen image for the opening of my website using React and Material UI. Here's a snippet of my JSX code with the default Material UI theme: <AppBar> //code in between </AppBar> <Container sx={{margin: ...

The API response appears to be a successful 200 status code, however the actual result is a

I'm currently working with a VUEJS / VUEJS Resources code snippet that retrieves data from an API service. fetchData: function(name){ var self = this; self.$http.get('http://www.apiservice.com/', { params: { ...

How to reset or clear the RangePicker in Ant Design for React

I am working with a component similar to this one and I am looking for a way to make it automatically reset after the user selects a date. Currently, once a date is selected, it remains as is until manually cleared. Current behavior: Desired behavior: ...

How is it possible for the igx-expansion-panel to close when there is a nested angular accordion present?

Currently, I am faced with the challenge of closing the igx-expansion-panel within my Angular project. While everything functions smoothly with a standard panel, things get a bit tricky when dealing with nested angular accordion structures using igx-accord ...

Enhance user experience by implementing an autocomplete feature for a text input field

Can you name the process in which a form is automatically filled using database information without needing to refresh the page? One common example of this technique is seen on platforms like Google or Facebook, where they predict friends you may be searc ...

Transforming an Excel document into JSON format: inspection of JSON code structure

Looking to transform Excel data into JSON format, but unsure if the current structure will be ideal for processing with D3.js. Planning to incorporate this JSON file within D3.js for visualization purposes. Here's a snippet of the Excel file: In the ...

What could be causing the Access-Control-Allow-Origin error to appear when attempting to access a page using ajax?

As I attempt to utilize Ajax to retrieve data from my website using a script that should be able to execute from any location, the Ajax code within my script is structured like this: var ajax = new XMLHttpRequest(); ajax.open('GET', 'http:/ ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

Refreshing and paginating data tables

I'm currently working on a basic CRUD data table and I have added a refresh function using AJAX to dynamically append HTML without reloading the page. Everything was working fine until I introduced pagination from Laravel. The issue now is that only t ...

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

Including folders recursively using Node.js

Currently, I am in the process of setting up test automation using yarn, selenium, and node js. In the wdio.conf.js configuration file, there is a requirement to specify a specs array that contains strings representing paths to various js files for executi ...

Function that is triggered repeatedly when modifying the state within it

Within my render method, I am calling a handlePageClick function like this: onPageChange={this.handlePageClick} The function itself looks like this: handlePageClick = data => { this.setState({ circleloading: true }); let names = ...

Issue with VUE JS: Score not increasing on click event as desired

Greetings! I've been working on a basic game that increments the score by 1 when the user clicks a button. new Vue({ el: '#MyApp', data: { score: '10', }, methods: { ScoreIncre: function(incre) { this.score ...