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

Widget class with an AJAX function

I designed a custom WordPress Widget that fetches the latest posts. Initially, it retrieves a specific number of posts and provides a button for users to load more posts through AJAX. Here is the complete code for the Widget: /* recent posts Widget ==== ...

Retrieving a particular key and its corresponding value within a jQuery object

In my current project, I have a PHP associative array where I am fetching keys and values and passing them to a jQuery object: $names = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); $js = json_encode($names); echo 'var names= ' . $js ...

A step-by-step guide to implementing lodash once in Vuejs

I am faced with the following input scenario. <input type="text" maxlength="50" v-on:input="query = $event.target.value" v-on:keyup.enter="once(search)" /> Additionally, there are ...

Is it possible to dynamically insert a ng-mouseover in AngularJS using Javascript?

It seems like there is an issue with this code: var run_div = document.createElement('div'); run_div.className = 'whatever'; run_div.textContent = 'whatever'; run_div.setAttribute('ng-mouseover', 'console.log(&b ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

Font Awesome solely alters the font size within html, rather than css

<i class="fa fa-graduation-cap" aria-hidden="true" style="font-size: 50px;"></i> It's functioning properly. .fa-graduation-cap { margin-top: 38px; color: #E46A6B; font-size: 50px; } Not working too well. This issue is new to me. Any th ...

Facing an issue with webpack-dev-server where it displays a blank screen

Hello! I am currently in the process of creating my first MERN stack application, using Webpack as the build tool. The main objective is to have Express serving the APIs for the app and webpack-dev-server handling the static content (from my static directo ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

The value of the jQuery data on click event handler becomes 'undefined' when used within an AJAX handler

When I click on the Positive or Negative buttons, a jQuery event handler function is triggered. Each button passes different data objects to the handler. However, within the AJAX POST handler, I am unable to access the data from the click event. $('# ...

Encountering an issue with compiling Angular due to a Type Inference error

interface Course { name: string; lessonCount: number; } interface Named { name: string; } let named: Named = { name: 'Placeholder Name' }; let course: Course = { name: 'Developing Apps with Angular', lessonCount: 15 }; named = ...

Unlock the power of JavaScript and jQuery by utilizing inner functions

Here's some JavaScript and jQuery code with an ajax request included. Can you solve the mystery of why success1() can be called, but not this.success2()? Any ideas on how to fix this issue? function myFunction() { this.url = "www.example.com/ajax ...

Inspecting Ajax response for specific CSS class - is it possible?

I am utilizing Ajax to send a request to a .Net MVC controller, which then returns HTML content to be displayed on a specific section of the webpage. My goal is to identify if this HTML contains a class name so that I can use it to update another section o ...

PHP - Is it possible to transfer the name of a POST method from one page to another in PHP?

How can I retrieve and check the value of a select option from one page to another using PHP? Specifically, I want to access the POST name ($_POST['selection_value']) and validate if it matches a certain selection value (e.g., 'time'). ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Warning: Datatables encountered an issue with the table ID 'example'

Good day, I am seeking clarification regarding DataTables. In a tutorial, I came across a table that can be edited "inline". I prefer the table to be in German. The code snippet for the table: <script type="text/javascript" language="javascript" ...

Looking for help with aligning an icon to the right side of my text

I'm struggling with aligning the icon to the right of the quantity. When I use float:right, it places the icon at the far right of the cell instead of next to the text. Is there a way to get it to be on the right side of the text but directly adjacent ...

Is there a way to set up a local npm module directory without using symlinks

Here is a breakdown of the file structure in a simple way. /my-module ..package.json /my-app ..package.json I am trying to have my-app install my-module locally. This is what I have attempted: "dependencies": { "myModule": "../my-module" } The opti ...

The Datatable fails to render the JSON data

Currently, I am dynamically binding a DataTable from a JSON URL and also generating headers dynamically. However, I am facing some issues in passing the JSON data to aaData in the DataTable. Can you please take a look at my code snippet below and provide m ...

Guide on sending JSON return data as a parameter to a URL route in Laravel

Currently working on a project in Laravel and I have successfully integrated a search feature to search for users within a database utilizing twitter typeahead supported by jQuery. However, I've encountered a roadblock. My aim is to pass the returned ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...