Using JavaScript to change images from an array into img elements with a specific class

I am working on code that attempts to display temporary images from `tempimages[]` onto the `img src` with `id=slide` within the `box002` class, based on a random number chosen from `arrayVariable` and assigned to `ptag[i]`.

The objective is to initially show `tempimages[0]` on the `img src` in the `box002` class. After dropping an image, it should be deleted by the function `Drop(ev)`. Subsequently, each `tempimages[i]` should be displayed on the `img src` of `box002` upon each drop.

How can I display images from an image array `tempimages` onto the `img src` within the box with the class `box002`?

Although I tried using the function `displayAllImages()` to assign images to the `img src` with `id=slide`, it did not successfully display the images.

`box002` elements are draggable and can be dropped into any box.

The goal is to sequentially display each image from `tempimages[]` onto the `img src` within the box after each drop. How should I modify the code to achieve this functionality?

var tempimages = [];
function rvalue() {
var array = [];
 var arrayVariable = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
  var ArrayOfImages = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'];

  arrayLength = arrayVariable.length;
  ptags = document.getElementsByName("values");

  for (i = 0; i < ptags.length; i++) {
    ptags[i].innerHTML = arrayVariable[Math.floor(Math.random() * arrayLength)];
    array.push(ptags[i].textContent);
    tempimages.push(`${ptags[i].textContent}.jpg`); // want to display array to box002 to imgtag
 }
}

function displayAllImages() {
  var 
    i = 0,
    len = tempimages.length;    

  for (; i < tempimages.length; i++) {
    var img = new Image();
    img.src = tempimages[i];
    img.style.width = '100px';
    img.style.height = '100px';

    document.getElementById('slide').appendChild(img);
  }
};

$(function() {
  displayAllImages(); 
});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();

  var data = ev.dataTransfer.getData("Text");
  var el = document.getElementById(data);

  el.parentNode.removeChild; // deleting drag item
  ev.target.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none

  var pParagraph = ev.target.firstElementChild;
  ev.target.removeChild(pParagraph);
  alert(el);
}
#container {
  margin-top:-2%;
  white-space:nowrap;
  text-align:center;
  margin-left:20%;
  margin-right:30%;
}

.box {
  background-color: coral;
  width: 60px;
  height:60px;
  margin-top:10px;
  display:inline-block;
  border-radius:5px;
  border:2px solid #333;
  border-color: #e6e600;
  border-radius: 10%;
  background-color:  #ffcc00;
}

.box002 {
  float: left;
  width: 50px;
  height: 50px;
  float: left;
  margin-left:30%;
  padding-top:2%;
  background-color:#ffff00 2px;
  border:2px solid #000066;
}

.text {
  padding: 20px;
  margin:7 px;
  margin-top:10px;
  color:white;
  font-weight:bold;
  text-align:center;
}

#container {
  white-space:nowrap;
  text-align:center;
  margin-left:20%;
  margin-right:30%;
}

.text {
  padding: 20px;
  margin:7 px;
  margin-top:10px;
  color:white;
  font-weight:bold;
  text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body onload="rvalue()">
  <div id="container">
    <div class="box"  ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
      <p name="values"></p>
    </div>

    <div class="box"  ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
      <p name="values"></p>
    </div>

    <div class="box"  ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
      <p name="values"></p>
    </div>
  </div>

  <div class="box002" draggable="true" ondragstart="drag(event)" id="2">
    <img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>    
  </div>    
</body>

Answer №1

It seems like you're not entirely certain about what you're trying to accomplish, but I have a suggestion that might help you reach your goal. The code below selects three items at random and updates the image in the slide element every time the slide is dropped on one of the boxes.

I've made some modifications to the code based on my initial understanding. When reviewing the original code, I noticed redundant arrays, so I combined them into a single array for simplicity.

var tempimages = [];

function rvalue() {
  const
    items = [  
      { label: '1', url: 'https://via.placeholder.com/75x75?text=1' },
      { label: '2', url: 'https://via.placeholder.com/75x75?text=2' },
      { label: '3', url: 'https://via.placeholder.com/75x75?text=3' },
      { label: '4', url: 'https://via.placeholder.com/75x75?text=4' },
      { label: '5', url: 'https://via.placeholder.com/75x75?text=5' },
      { label: '6', url: 'https://via.placeholder.com/75x75?text=6' },
      { label: '7', url: 'https://via.placeholder.com/75x75?text=7' },
      { label: '8', url: 'https://via.placeholder.com/75x75?text=8' },
      { label: '9', url: 'https://via.placeholder.com/75x75?text=9' },
      { label: '10', url: 'https://via.placeholder.com/75x75?text=10' }
    ],
    ptags = Array.from(document.querySelectorAll('[name="values"]'));
    
  ptags.forEach(ptag => {
    const
      // Generate a random index.
      randomIndex = Math.floor(Math.random() * items.length),
      // Get the item from the random index (may result in duplicates).
      item = items[randomIndex];
    // Update the label
    ptag.textContent = item.label;
    // Add the selected item to the array.
    tempimages.push(item);  
  });
}

function displayAllImages() {
  // Exit if there are no more images in the array.
  if (tempimages.length === 0) {
    return;
  }
  
  const
    // Remove the first item from the array.
    item = tempimages.shift(),
    // Select the image element.
    image = document.getElementById('slide');
  // Update src attribute with new URL.
  image.src = item.url;
};

$(function() {
  // Call rvalue before displayAllImages on load.
  rvalue();
  displayAllImages(); 
});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();

  var data = ev.dataTransfer.getData("Text");
  var el = document.getElementById(data);

  el.parentNode.removeChild; // remove dragged item
  // Set the box's background color back to default when dropping.
  ev.currentTarget.style.backgroundColor = 'initial'; 

  var pParagraph = ev.currentTarget.firstElementChild;
  ev.currentTarget.removeChild(pParagraph);
  
  // Load next image in the slider.
  displayAllImages();
}
#container {
  margin-top:-2%;
  white-space:nowrap;
  text-align:center;
  margin-left:20%;
  margin-right:30%;
}

.box {
  background-color: coral;
  width: 60px;
  height:60px;
  margin-top:10px;
  display:inline-block;
  border-radius:5px;
  border:2px solid #333;
  border-color: #e6e600;
  border-radius: 10%;
  background-color:  #ffcc00;
}

.box002 {
  float: left;
  width: 50px;
  height: 50px;
  float: left;
  margin-left:30%;
  padding-top:2%;
  background-color:#ffff00 2px;
  border:2px solid #000066;
}

.text {
  padding: 20px;
  margin:7 px;
  margin-top:10px;
  color:white;
  font-weight:bold;
  text-align:center;
}

#container {
  white-space:nowrap;
  text-align:center;
  margin-left:20%;
  margin-right:30%;
}

.text {
  padding: 20px;
  margin:7 px;
  margin-top:10px;
  color:white;
  font-weight:bold;
  text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="container">
    <div class="box"  ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
      <p name="values"></p>
    </div>

    <div class="box"  ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
      <p name="values"></p>
    </div>

    <div class="box"  ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
      <p name="values"></p>
    </div>
  </div>

  <div class="box002" draggable="true" ondragstart="drag(event)" id="2">
    <img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>    
  </div>    
</body>

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 UI Datepicker extending beyond its bounds

My Datepicker is expanding and filling the entire screen. What could be causing this issue? Here is my code: Additionally, how can I change the date format in jQuery to appear as dd-mm-yyyy? https://i.stack.imgur.com/IQzVV.png HTML: <!DOCTYPE html&g ...

What is the process for importing a JavaScript export file created from the webpack.config file?

Issue at Hand In the process of testing APIs, I encountered a dilemma in setting up either the DEV or Production environment. This involved configuring API endpoints for local testing and preparing them for production use. To achieve this, I utilized NOD ...

Is it possible to achieve a file upload in splinter using Python?

A challenging task lies ahead with my web application, where users can upload XML-style files and make modifications directly in the browser. To test this scenario using Splinter, I need to ensure correct input (id="form-widgets-body"): https://i.sstatic ...

Is it possible for HTML5 Web Audio to match the high quality of a DAW?

Calling all sound enthusiasts! I recently stumbled upon a couple of fascinating videos here and here about the Web Audio API in javascript and its applications in music production. I'm curious, can this API produce sound quality comparable to popular ...

Attempting to transfer various variables from several windows using AJAX

Is it possible to pass multiple variables from two different windows into the same PHP script? If not, what would be the best approach to take? Thank you. verifyemail.html <script type = "text/javascript" src = "js/js_functions.js"></script> ...

Transferring an object containing circular references from the server to client-side Javascript without losing its circular structure

Trying to send an object with circular references from a node.js server to client-side JavaScript is proving to be a challenge. On the server side (node.js): var obj = { circular: obj } //.... app.get('/', function(req, res){ res.render ...

Using ASP.NET MVC to incorporate RenderAction with dynamic JavaScript parameters

Is there a way to pass a JavaScript variable into an MVC RenderAction parameter? @{Html.RenderAction("GeneratePlayersSelect", new { teamid = ??? ] });} I would greatly appreciate any assistance on this. Thank you in advance. ...

"Troubleshooting the inconsistency of GraphQL resolver context functionality between Playground and the client in the official NextJS starter

Currently, I am making adjustments to my NextJS/Apollo application to enable SSG with GraphQL API routes. I have referenced this official NextJS starter example as a foundation for configuring the client. An issue arose in my application which led me to g ...

Compass - substitute a single value for an alternate attribute

Can I utilize a value from one class to customize another? Consider the following class: .sourceClass { color: red; } And now, let's say we have this class: .destinationClass { border-color: ###needs to match the color in .sourceClass => re ...

Error: Property "rotation" cannot be redefined

After setting up all the necessary dependencies using npm and bower for a project on a different laptop, I encountered an error when trying to run it locally. The error message reads: Uncaught TypeError: Cannot redefine property: rotation at (line 7542 i ...

Angular JS Profile Grid: Discover the power of Angular JS

I came across an interesting example that caught my attention: http://www.bootply.com/fzLrwL73pd This particular example utilizes the randomUser API to generate random user data and images. I would like to create something similar, but with manually ente ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

Tips for showcasing retrieved JSON with jQuery's ajax functionality

Below is the jquery code I am working with: $.ajax({ type: "POST", url: "Ajax/getTableRecord", data:{ i : id, t: 'mylist'}, dataType: 'json', success: function(data){ alert(data); ...

What is the best way to nest a div within a flexbox container?

I am attempting to create a div that is based on percentages, and I want to nest a div inside another. Specifically, I want the center (xyz div) to only take up 90% of the height of the content-div. My goal is for the "content" div to be responsive to 90% ...

The post request fails to send certain variables

I'm experiencing an issue with a form that has rows structured like this: <div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeNam ...

What is the best way to simulate an unexported function in Javascript jest environments?

Testing a module in my vuejs project is what I'm currently focusing on. import { getBaseUrl } from "@/application/api/baseUrl"; export default ( uri: string, requestBody: Record<string, string | number> ): void => { let form ...

Can the site be shown in the background?

I have a unique idea for a games website that I want to share. It's a bit difficult to explain, so please bear with me as I try to convey my vision! The inspiration for this project comes from a website called . Have you seen it before? The concept i ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Rendering a child component beyond the confines of its parent component in React.js: A Step-by-Step Guide

I am working with a table component that has sticky headers and dropdowns, ellipsis menus, and other complex components within the table body rows. Each row of the table contains nested table body rows, and the parent rows stick to their child rows. Howeve ...

javascript The final position achieved through requestAnimationFrame is never precise

let pf = document.querySelectorAll('.pf'); for (let i of pf) { Object.assign(i.style, { left: '400px' }) } function shiftLetters() { let start = performance.now(); let dist = -400; let dur = 500; const logoAnimate = ( ...