Creating an array of images using input fields and showcasing them as a dynamic slider

I'm currently working on a challenge involving creating an array of images using an input field and then displaying the array of images as a slider in JavaScript. If anyone can help me, please provide a solution.

Could you kindly share the JavaScript code for this?

document.querySelector("#a").addEventListener("change", function(){
    const reader = new FileReader();
    reader.addEventListener("load", () => {
        localStorage.setItem("recent-image", reader.result)
    });
    reader.readAsDataURL(this.files[0]);
});
document.addEventListener("DOMContentLoaded()", () => {
    
    const imageurl = localStorage.getItem("recent-image");

    if(imageurl){
        document.querySelector("#b").setAttribute("src", imageurl);
    }
});

Is it possible to achieve this with an array? Please let me know your answer.

Currently, only one image is being stored, but I would like to be able to store multiple images in local storage using an array. Can you assist me with this?

Answer №1

The main issue here is establishing the local storage to store the images for later retrieval and display. Below is a sample solution:

var images = localStorage.getItem('images') || [];

function saveImages() {
    localStorage.setItem('images', JSON.stringify(images));
}

function drawImages() {
    var slider = document.getElementById('slider');
    slider.innerHTML = '';
    for (var i = 0; i < images.length; i++) {
        const img = images[i];
        const html_img = document.createElement('img');
        html_img.src = img;
        html_img.alt = 'Alt img';
        html_img.width = 200;
        html_img.height = 150;
        slider.appendChild(html_img);
    }
}

document.querySelector("#a").addEventListener("change", function(){
    const reader = new FileReader();
    reader.addEventListener("load", ()=>{
        images.push(reader.result);
        drawImages();
    });
    reader.readAsDataURL(this.files[0]);
});

document.addEventListener("DOMContentLoaded()", drawImages);

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

What are the steps to conducting a search on mongodb?

My document list is shown below [{"userId": "1", "text": "National security is of utmost importance"}, {"userId": "2", "text": "We must ensure a strong defense while upholding civil ...

A beginner's guide to efficiently indexing tables in AngularJS

Having Trouble with ng-repeat Indexing <tr ng-repeat="Ward in Wardresult "> <td>{{$index + 1}}</td> ...................... some column ....................... </tr> Although, the output ...

Error: Unforeseen token encountered while attempting to import React in Javascript

Upon executing the command 'npm run start', I encountered this error: import React from 'react'; ^^^^^ SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:721:23) at Object.Module._exten ...

The `user-select: none` property displays distinct behavior in Safari

My Goal I am in the process of creating an input-like content editable div. The idea is to click on tags outside the div and insert them inside the div while still being able to type around these tags. The Issue and Reproduction Steps To prevent tag but ...

Class selectors can be used for jQuery drag and drop functionality

Seeking help from experienced individuals, as I am new to JS/jQuery. I have come across a script for drag and copy functionality which I have customized to fit my needs. However, the script currently uses "id" selectors and I wish to switch to using "class ...

Notify users of any unsave changes before allowing them to navigate to a different page in ReactJS

I have a unique challenge with a dynamic form in which it automatically submits when all required fields are filled out, without a submit button. Imagine a user fills out some fields and then tries to leave the form by clicking a navigation link on the app ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

Transform the date and display it for every element in a PHP array

I am currently working on outputting a list of dates in the format 2012-06-18 to an XML file. foreach ($result_array as $date) { echo "<market date=\"".$date['saledate']."></market>\n"; } Everything seems to be working ...

How can I extract a substring using jQuery?

<script type="text/javascript"> $(function(){ $("a[rel='tab']").click(function(e){ e.preventDefault(); pageurl = $(this).attr('href'); $.ajax({url:pageurl+'?rel=tab',success: function(data){ $(&apos ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...

Visualizing data in Angular js using JSON Object

I am currently working on implementing chart representation in AngularJS. While I have successfully implemented simple charts, I now need assistance with converting the below JSON data into arrays for chart representation: [{"value": {"DE":2,"NP":20,"BD" ...

What is the process for switching a button on and off?

I am attempting to add a data to an array when a button is pressed, and then remove it from the array when the button is pressed again (while also changing the button's class). <button *ngFor="#color of colors" [class.selected]="color = ...

Tips for identifying a pair of numbers (with varying ranges) in which one number must be present at all times

I am currently trying to understand the regex I have implemented in Angular 2 using Typescript: /[0-5]?[0-9]?/ Surprisingly, this regular expression works flawlessly to match any valid minute from 1 to 59, even though it seems like an empty string would ...

Ways to integrate an HTML document into a Python tkinter GUI window

I'm looking to integrate my HTML webpage project into a Python Tkinter window using Tkinter HTML view. However, when attempting to do so, the end result in the Python Tkinter window looks like this: what I'm getting. Contrary to that, here is wha ...

Error: Module not located or Image unable to load in React JS

Here is the structure of my project : src -assets fut.png -components -admin_dashboard Sidebar.js -App.js -pages Dashboard.js I encountered an issue trying to load the image fut.png from the file Sidebar.js. Even after attempting ...

Input the chosen icon list values into a designated box

As a beginner in the world of Javascript, I am venturing into creating a password generator that involves using icons. The concept is simple - by clicking on any number of icons from a list, the corresponding hex code will be displayed in an input box. The ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

What causes the entire page to refresh when I attempt to adjust the font size using jQuery?

On my website, I am trying to create a button that will increase the font size when clicked once and decrease it when clicked again. I have written some jQuery code to achieve this: $("p").css("font-size","20") But after clicking the button, the font siz ...

Encountering a compile-time issue while constructing a basic partial array class in C++

I'm struggling with the compilation of my Partial Arrays class. When trying to call a previous member function within one of my functions, I encounter the error message "member reference base type 'ITEM_TYPE [255]' is not a structure or unio ...

Firebase Database Integration with AngularJS: Loading Results Dynamically upon Button Click or Action

Even though I can successfully retrieve data from my Firebase database, the scopes in my AngularJS application aren't updating automatically. It seems like the issue lies within AngularJS, but I'm unable to pinpoint the exact cause. Below is the ...