Creating and displaying images dynamically on a webpage using JavaScript after it has finished loading

I am trying to load images from an array and display them on a webpage upon the browser window loading. Here is my approach:

const players = [
    {
     photo: 'img/photo0.jpeg'
    },
    {
     photo: 'img/photo1.jpeg'
    },
    {
     photo: 'img/photo2.jpeg'
    }]

// This function should achieve that.
    function() {

      for(i = 0; i < players.lengh; i++;){
      }
    }

Answer №1

To utilize the onLoad function, you can simply access it via the window object.

window.onload = function() {
  // Add your desired actions for when the page loads
};

Answer №2

let container = document.querySelector(".container");

      const items = [
        {
          image: "img/item0.jpeg",
        },
        {
          image: "img/item1.jpeg",
        },
        {
          image: "img/item2.jpeg",
        },
      ];

      function displayItems() {
        // Clear the container to reflect any changes made to it
        container.innerHTML = ``;
        // Create a template to display images
        let htmlStr = ``;
        for (let item of items) {
        // Dynamically create images in the template string
          domStr += `
                  <img src=${item.image} width=200 height=200>
                  `;
        }

        // Concatenate the strings with images and attach them to the container element
        container.innerHTML = htmlStr;
      }

      // Call the displayItems function when the window loads
      window.addEventListener("load", (event) => {
        displayItems();
      });
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="container"></div>
  </body>
</html>

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

jQuery causing trouble with AJAX in Rails

Currently, I am fetching a list of users from the controller side and generating the HTML code to append it. This is how I wrote the code: $.ajax({ type : "get", contentType : "application/json; charset=utf-8", url : "/users/sear ...

Using NodeJS with Jade to handle a dynamic number of blocks

As I dive into NodeJS development, a challenge has presented itself... In my project, there is a main template called layout.jade that sets up the top navigation bar using Bootstrap on every page. This specific application focuses on music, where each art ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Reducing the size of textures in three.js

Is it possible to shrink the faces of a model rendered in the browser using Threejs, without affecting the mesh structure? I am looking for suggestions on how to accomplish this unique task. ...

What is a more efficient method for writing HTML in JavaScript compared to document.write?

A helpful JavaScript code snippet for a jQuery mobile app can be found here. After finding it, I made some slight adjustments to suit my needs. Being a beginner in JavaScript and currently taking a course on Codecademy, I recently learned that document.wr ...

Issue with JQuery: Logo only becomes visible after scrolling

Recently, I added a jQuery script to modify the header as we scroll on our website. Everything is functioning smoothly except for one issue - the large logo on the left side doesn't appear when visitors first land on the page; it only shows up after t ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

Issue with Jquery: Checkbox fails to get checked in Internet Explorer 7

Having trouble with checking a checkbox, I've attempted the following steps: $('#someId').attr('checked','checked'); $('#someId').attr('checked', true); Both of these methods are effective for I ...

What's the best way to ensure uniform card height in Material-UI?

Is there a way to ensure consistent card height in Material-UI without setting a fixed height? I want the card heights to dynamically adjust based on content, with all cards matching the tallest one on the website. How can this be achieved while also addin ...

Looking for a node.js asset manager for converting coffeescript, jade, and stylus files to JS and CSS?

I specialize in using coffeescript, jade, and stylus for my projects. My task involves creating two separate "one page apps" where I need to include all assets within the initial payload. My goal is to consolidate, compile, and merge all coffeescript fil ...

Unable to display an image prior to its upload

I'm facing an issue with changing the image for my second data. It's not updating, but when I try it with the first data, it works fine. I'm unsure why this is happening and would appreciate any help in resolving it. Here is the form where ...

Creating equal height columns with Bootstrap 4 and aligning a button to the bottom of each

Hey there, I'm facing an issue with bootstrap equal height columns. I have a row with 3 columns, and within each column, there is a div with a class of "h-100" to make the columns equal height and add a border. This creates a visual gap between the co ...

Creating tables with equal column width in Bootstrap 5

Is there a method to ensure equal width for all columns in a bootstrap table? By default, it appears to allocate more space to columns with larger content, but I want them all to have the same width. Below is my code: <table class="table table-hove ...

Tips for iterating through data in JSON format and displaying it in a Codeigniter 4 view using foreach

As a newcomer to JSON, I have a question - how can I iterate through JSON data (which includes object data and object array data) using jQuery/javascript that is retrieved from an AJAX response? To illustrate, here is an example of the JSON data: { "p ...

Having trouble getting my Jquery Ajax post request to work with JSON data

I am working on syncing data from my Phonegap app back to the server. I have a PHP script set up on the server to handle the incoming data and now I need to figure out how to post values from my App to this script. Currently, I store my data in a SQLite d ...

Struggling with passing attributes to an AngularJS directive? You might be encountering the frustrating issue of receiving undefined values for

Currently, I am working on a directive that has four parameters being passed to it, all of which are bound to the directive scope. The problem I am facing is that despite the data existing and being loaded, the directive is receiving all values as undefin ...

What are the steps to create a login form that is responsive by utilizing the Bootstrap grid system

.custom-border { border: 2px groove #000 !important; padding: 0px 5.4em 1.4em 6.4em !important; margin: 0 0 1.5em 0 !important; box-shadow: 0px 0px 0px 0px #000; margin-top: 30px !important; } .custom-legend { font-size: 1.2em !important; te ...

Having trouble getting Handsontable to scroll smoothly in Chrome?

I'm currently facing an issue with handsontable specifically on Chrome. The problem is that although the table itself is scrollable, the values and row headings within the table do not update as they should. You can see the issue illustrated in the im ...

Navigate to the following slide by clicking on BxSlider

Looking to enhance the navigation on my slideshow by using the slide itself as a next button, instead of relying on traditional prev/next controls. Although it seems like a simple feature to implement, I'm struggling to make it work. This is my curre ...