Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in every single placeholder. What could be causing this issue?

Here's the JS code I'm working with:

(function pushImages() {
  //array of images, better to store in an object ?
  var images = ["07750013.jpg", "07750015.jpg", "07770021.jpg", "08210019.jpg", "08220021.jpg", "08230008.jpg", "08240009.jpg", "14990007.jpg",       "15000008.jpg", "15000009.jpg", "15010024.jpg", "15020018.jpg", "15020021.jpg", "15030012.jpg","15030025.jpg"];

  for (var i = 0; i < images.length; i++){
    //push the image to the markUp
    var newImage = images[i];
    var markUp = ("<img src='img/" + newImage + "' class='img-responsive'</img>");
    // get bootstrap place holder where to insert.after
    var placeHolder = document.getElementsByClassName("col-md-3");
      for (var h = 0; h < placeHolder.length; h++) {
        //insert the markUp into the html after the placeholder
        placeHolder[h].insertAdjacentHTML("beforeend", markUp);
      };
  };
})();

If you'd like to see the full code on Codepen, click here:

http://codepen.io/chem85/pen/grQJvP?editors=1111

I'm trying to incorporate this functionality into a larger app for a popup image gallery slider. While I could use a jQuery plugin for this purpose, I'm determined to figure it out using just JavaScript, without external plugins. Any guidance would be greatly appreciated. Thank you in advance.

Answer №1

After updating my response, the parent container now displays placeholders. Although I have not made changes to the CSS, you can adjust it accordingly based on the principle demonstrated.

HTML

<div class="container-fluid" id="photos-sections">
  <div class="row container" id="photos">

  </div>
</div>

JS

(function pushImages() {
                //array of images, better to store in an object ?
  var images = ["07750013.jpg", "07750015.jpg", "07770021.jpg", "08210019.jpg", "08220021.jpg", "08230008.jpg", "08240009.jpg", "14990007.jpg", "15000008.jpg", "15000009.jpg", "15010024.jpg", "15020018.jpg", "15020021.jpg", "15030012.jpg", "15030025.jpg"];
  var placeHolder = document.getElementsByClassName("container");
  for (var i = 0; i < images.length; i++) {

    var markUp = ("<div class='col-md-3'><img src='img/" + images[i] + "' class='img-responsive'</img></div>");
    placeHolder[0].insertAdjacentHTML("beforeend", markUp);

  };
})();

If you only intend to place one image in each container, there's no need to iterate through each image. Additionally, consider generating the number of placeholders based on the total number of images available.

Answer №2

When it comes to your specific requirement, there is no need to iterate through the placeholders individually. Instead, you can simply locate the placeholder with the corresponding index and insert the image into it.

(function placeImages() {
    //array of images, consider storing in an object for better organization
    var images = ["07750013.jpg", "07750015.jpg", "07770021.jpg", "08210019.jpg", "08220021.jpg", "08230008.jpg", "08240009.jpg", "14990007.jpg", "15000008.jpg", "15000009.jpg", "15010024.jpg", "15020018.jpg", "15020021.jpg", "15030012.jpg", "15030025.jpg"];

    for (var i = 0; i < images.length; i++) {
          //insert the image into the markUp
          var newImage = images[i];
          var markUp = ("<img src='img/" + newImage + "' class='img-responsive'</img>");
          // find the bootstrap placeholder where the image will be inserted after
          var placeHolder = document.getElementsByClassName("col-md-3");

          placeHolder[i].insertAdjacentHTML("beforeend", markUp);

       };
})();

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

The JSX component cannot use 'Router' as a valid element

Error Message The error message states that 'Router' cannot be used as a JSX component because its return type 'void' is not a valid JSX element. TS2786 import App from './App'; 5 | > 6 | ReactDOM.render(<Router ...

Is there a way for me to update the button text and class to make it toggle-like

Is there a way to switch the button text and class when toggling? Currently, the default settings show a blue button with "Show" text, but upon click it should change to "Hide" with a white button background. <button class="btn exam-int-btn">Show< ...

Unexpected behavior in jQuery AJAX: XML response returned as #document instead of object

I'm encountering an issue with jQuery where, when attempting to retrieve an XML document, it returns as #document in the console instead of a usable object. What could be causing this behavior? This is the JavaScript code I am using: $.get('/in ...

Access-Control-Allow-Headers does not allow the use of X-Requested-With

I'm currently working on a system that includes an add item to cart feature. This functionality involves using Jquery's $.ajax method. However, I've encountered an error when attempting to access the online server - "XMLHttpRequest canno ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

Tips for implementing visual alterations using dynamically generated HTML scripts

When I dynamically generate HTML code from markdown, I typically wrap it in the <p></p> tag like so: <p class="embedded_markdown"> ... <h1>...</h1> ... <h3>...</h3> ... </p> I decided to experiment with sho ...

Using the Ternary Operator in JavaScript to Dynamically Update HTML Elements with Angular

Is there a way to convert the code below into a ternary operator so that it can be used in an .HTML file? statusChange && statusChange === 'Employed' ? true : employmentStatus === 'Employed'; To clarify, I want to assign the re ...

Eliminate HTML field based on checkbox status

I'm looking to dynamically remove HTML fields based on a Yes/No condition. I've shared the code below for better understanding. If Yes is selected, I want to hide the No Field/Input/Box and vice versa. function AutoCheck() { if (document.getEl ...

Tips for utilizing JSON and ajax smoothly without encountering any errors

I am attempting to retrieve JSON data from an external PHP file using AJAX and populate it into a dropdown list. After successfully setting up XAMPP with Apache and Mysql, I managed to make everything work for one JSON object. However, when I tried adding ...

Is there a way to increment a counter with a click?

Seeking a method to create a counter that increments upon button click. Attempted code provided below, however the displayed value remains constant: $(document).ready(function () { $("#gonder").click(function() { var baslik = document.title; ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Ways to effectively utilize the results from php functions triggered by ajax in our document

I have a mobile application that constantly updates latitude and longitude values to my PostgreSQL database. I am attempting to display these updated points on an OpenLayers map using jQuery and AJAX. However, I am encountering a problem: after clicking th ...

Is it possible to refresh the JSViews data that is underneath using an onclick event?

I have created a photo gallery using a JSViews template which includes upvote and downvote buttons. When these buttons are clicked, it triggers a database update to increase the score. However, I am facing an issue with updating the Score field in the HTML ...

Challenges with creating a contact form using bootstrap modal

I'm facing an issue with a bootstrap modal contact form. It works fine on all browsers except for iPad/Safari. Can anyone help me figure out what's wrong? On iPad, the modal is positioned to the right and down the page instead of in the cente ...

Incorporate Jquery Append and Each functions into Class addition

I've encountered an issue while trying to retrieve information in JSON format and add an ID to each element. Despite my efforts, my code is not functioning as intended. Although the appending process is successful and I can see all my results in JSON ...

Encountering excessive re-renders while using MUI and styled components

Hey there! I recently worked on a project where I used MUI (Material-UI) and styled-components to render a webpage. To ensure responsiveness, I made use of the useTheme and useMediaQuery hooks in my web application. My goal was to adjust the font size for ...

Ensure your Vue components have type-checked props at compile time when using TypeScript

I have encountered an issue while using Vue.js with Typescript. The code I am working with is pretty straightforward, utilizing vue-class-component and vue-property-decorator. <script lang="ts"> import { Component, Prop, Vue } from 'vue-pro ...

Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect. Below is the HTML search ...

Steps for adding a delete icon to a text input field and enabling the functionality to delete text

In the code snippet below, I am creating a text input field: <input type="text" class="signup-input text-value" name="" placeholder="e.g. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d48554c405d41486d">[email pro ...

How to convert a querydict with multiple objects into lists

When I send an array of JavaScript objects to a Django view via AJAX, the object structure is as follows: [{'oid':'id1','oiid':'iid1'},{'oid':'id2','oiid':'iid2'}] This is ho ...