No output from JavaScript loop when trying to print an array

I've been looking all over the place and haven't been able to find a pure JavaScript solution for my problem that I can implement into my code. The issue involves a script that is meant to display an array of images, but currently it only displays one image from the array.

Here is the relevant HTML code:

<div id="imgViewer"></div>
<script>
var imgViewerImages = ['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
</script>
<script src="services/imgViewer.js"></script>

And here is the JavaScript code:

function imgViewerPrinter(){
    var imgViewerTarget = document.getElementById('imgViewer');
    imgViewerImages.toString();

    for (var i=0;i<imgViewerImages.length;i++){
        imgViewerTarget.innerHTML = '<img src="' + imgViewerImages[i] + '">';
    }
}

window.onload = imgViewerPrinter();

As I am still new to JavaScript, I kindly ask for your patience and assistance in solving this problem. Thank you in advance!

Answer №1

attempt :

imgViewerTarget.innerHTML += "<img src="' + imgViewerImages[i] + '">";

Answer №2

To display an array of images, it is important to incorporate your HTML code within a loop to effectively showcase each image. For instance, the following code snippet demonstrates how you can iterate through an array of image files:

 for (var i = 0; i < imgViewerImages.length; i++){
    var imgPath = 'img/imgViewer/' + [i] + '.png';
}

Answer №3

Check out this improved solution.

var imagesToShow =['img/imageGallery/1.jpg','img/imageGallery/2.jpg','img/imageGallery/3.jpg','img/imageGallery/4.jpg','img/imageGallery/5.jpg','img/imageGallery/6.jpg'];

function displayImages(){

    var imageList=[];
    for (var i=0;i<imagesToShow.length;i++){
        imageList.push('<img src="' + imagesToShow[i] + '" />');
    }
     var galleryTarget = document.getElementById('imageGallery');
     galleryTarget.innerHTML = imageList.join('');
}

window.onload = displayImages();

Answer №4

If you're looking for a better approach, consider trying this out. When your code constantly rewrites innerHTML, it ends up displaying only the last updated value.

Instead of updating the DOM during each iteration, the code below will update your DOM just once:

function imgViewerPrinter(){
    var imgViewerTarget = document.getElementById('imgViewer');

    var imgViewerImages_length = imgViewerImages.length;
    var image = '';
    for (var i=0;i<imgViewerImages_length;i++){
        image += '<img src="' + imgViewerImages[i] + '">';
    }
    imgViewerTarget.innerHTML = image;
}

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

I am attempting to retrieve the initial three results from my MySQL database using Node.js, but I keep encountering an error

Below is the code I am currently using: con.query('SELECT * FROM tables', function(err, results) { if (err) throw err console.log(results[0].rawname) for(var i= 0; i <= 3; i++) { ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction. After imp ...

Having some trouble getting this jsfiddle to function properly on my local machine. Any suggestions?

I'm having trouble with this jsfiddle. It works perfectly for me, but when I try to replicate it, nothing happens when I press the button. Can anyone help? http://jsfiddle.net/KPEGU/1850/ Here is the code snippet: <html> <head> <ti ...

Is there a way to transfer a JSON map object from Flask and then utilize it as a JavaScript object?

python server code from flask import Flask, render_template, request import os import sys import json data_raw = [('0', '1', '0', '0'), ('0', '0', '1', '0'), ('1', ...

Encountering a problem when utilizing webview in react native due to an error with the evaluation of

While utilizing webview for trading charts, I am encountering an issue where a warning is displayed and the URL fails to load. Below is the code snippet used for loading. It seems like the video URI works fine in full screen mode, but other URIs are not ...

What is the method for selecting the col/row or x/y coordinates for N random elements from a 2D matrix without repeating any items or coordinates?

In my dataset, which is a 2D matrix, here is an example: data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]] I am looking to retrieve N random (x, y) indexes without any duplicates. Previously, I had a similar question and here is the solution I f ...

Plane is constantly cloaked in darkness

I'm having trouble adding a texture to my plane that repeats both horizontally and vertically. Every time I try to apply the texture, it shows up as black. I've attempted to add some lights to the scene, but the issue persists without any errors. ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

Express.js application experiencing technical difficulties

When attempting to create a simple Express application with the file called serv.js, I encountered an error. Here is the code snippet I used: var express = require('express'), app = express(); app.listen(3000, function() { c ...

Tips for creating a dynamic menu item that stands out with a highlighted style

I would like to add a colored square to highlight the active menu item. .main-menu ul { padding: 0; margin: 0; text-align: center; } .main-menu li { list-style-type: none; display: inline-block; padding: 40px 0; } .main-menu a { font-fam ...

Fire an event in JavaScript from a different script file

I have created a JavaScript file to handle my popups. Whenever a popup is opened or closed, I trigger a custom event like this: Script File #1 $(document).trigger('popupOpened', {popup: $(popupId)}); If I want to perform an action when the tri ...

Verify whether the object is inside the CSS border or CSS wrapper

As a newcomer to the programming world, I am venturing into my first jQuery project for my ICT school assignment. Here is an overview of the project: I have various draggable objects (images) within #wrapper, which is defined in my style.css file. ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

Tips for limiting the .click function to only the initial image in order to prevent loading all images within the container

I am facing a situation where multiple images are being returned into a specific div, which is working as intended. <div class="go" id="container"></div> Upon clicking on an image, it is loaded into a modal popup. However, instead of capturin ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

What improvements can be made to optimize this SQL query and eliminate the need for an additional AND statement at the end

I am working on dynamically constructing a SQL query, such as: "SELECT * FROM TABLE WHERE A = B AND C = D AND E = F" Is there a more efficient way to construct this SQL query without adding an extra AND at the end? Here is my current code snippet: le ...

What could be causing the lack of data for the current user?

I have been attempting to fetch the current user session and display the data in the view, but nothing is appearing. I even checked the database and confirmed an active session with all the necessary information. I attempted logging the user out and starti ...

Updating a specific field in a document using Node.js and MongoDB

Hey, I'm a beginner in nodeJS and I could use some help. I've been able to update an entire document easily but I'm struggling to update just a single value. Here's my code: router.patch("/:id", async (req, res) => { console.log(re ...

Creating a @HostListener that is activated only when the component is invoked

Using an Angular application with a ngx-datatable that autogenerates rows. Each row contains an action that triggers a popup of items, which is a separate component from the table. The popup is called from the table using a parent-child link as shown below ...