I am attempting to separate this "for" loop in order to generate five distinct DIV elements

Hello there! I am a beginner and I am attempting to create 5 different players by using some code that I found. Here is the code I have been working with: https://codepen.io/katzkode/pen/ZbxYYG

My goal is to divide the loop below into 5 separate divs for each player, rather than having them all under #audio-players:

function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}

Below is the code for the audio files:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];

I'm still learning and not sure how to proceed from here. Any help would be appreciated. Thank you!

Answer №1

If you're looking to set up multiple audio players, a simple solution is to loop through an array using the forEach method for better readability.

function createAudioPlayers() {
  files.forEach(function(f) {
    var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\">" + f + "</button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
    $("#audio-players").append(playerString);
  })
}

var files = ["interlude.mp3", // 0
  "chooseyourweapon.mp3", // 1
  "interlude.mp3", // 2
  "scriptures.mp3",
  "scriptures.mp3" // 3
];
createAudioPlayers()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="audio-players"></div>

Answer №2

Employ

for (f of files) {

instead of

for (f in files) {

For further information :

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

Enhancing website security using Content Security Policy in conjunction with Google Closure

Implementing CSP for my web application is a top priority. Here's the policy I have in mind: "default-src 'self' gap: cdvfile;" I rely on google closure for my javascript needs. However, it seems that without javascript optimization, my ...

Tips for Showing a Portion of an Object in React JS

Need help displaying subitems of an object. I can display the main item but struggling with subitems. Here's the attached image for reference: I'm having trouble displaying the comments section in the object. I'm using Django API and trying ...

Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed. <script> document.addEventListener('keydown', function(e){ e = e || window.event; key = e.keyCode || e.charCode; var keys = { 87: &ap ...

Dynamic modal in Vue JS with custom components

Within the news.twig file {% extends 'layouts.twig' %} {% block content %} <section class="ls section_padding_bottom_110"> <div id="cart" class="container"> <cart v-bind:materials=" ...

angular bootstrap dropdown opening on the left side

I am facing an issue with the angular bootstrap dropdown. I have successfully implemented it, as shown in this link. However, the problem is that the dropdown opens on the right side by default. Is there a way to make it open on the left side instead? Bel ...

Align a button within an input field to be in line with a stacked label in

I'm currently facing some issues with Ionic because it's not placing my button where I want it to be: https://i.stack.imgur.com/qtUQJ.png My goal is to have the button on the same line as the input, similar to the clear-button. This is the cod ...

Properly aligning sub-divs within a parent div using CSS

I'm facing a problem with my CSS styling that I need help with. Here is the screenshot of the issue I am trying to center align the inputs, each placed in its own div, within my form. Below is the HTML markup for the form: HTML Markup Code CSS st ...

Creating a webpage with HTML through C++

I've been experimenting with posting an HTML page using C++. I created a class that utilizes sockets to implement TCP socketing. After checking, it seems like the issue lies in what I am sending: string s = "<!DOCTYPE html><html><head& ...

Save a SQL query as a text file using Node.js

I'm having an issue with my code. I am trying to save the results of a SQL query into a text file, but instead of getting the actual results, all I see in the file is the word "object." const fs = require('fs'); const sql = require('mss ...

Transmit picture to server - HTTP Error 415 (Unsupported Media Type): "The media type 'image/png' in the request is not supported."

My attempts to send an image from the frontend using AJAX to the backend with Django Rest Framework have been unsuccessful. The error response received is: {"detail":"Unsupported media type \"image/png\" in request." ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...

Updating content dynamically in a MVC div element using AJAX

Working on an MVC application, I encountered a situation where I need to refresh a section of the page using AJAX... <div id="ajax" style="width:10%;float:left"> @foreach (var item in @Model.SModel.Where(x=>x.StudentId==13)) { <li>@Html.Dis ...

What is the best way to display a JavaScript object array on the screen

As someone who is new to JavaScript, I have a JavaScript object array that I would like to print the values of in the browser. However, I am unsure of how to do this without using document.write(vehicle); var vehicle = [{name:'Van',wheel:4,cha ...

Error parsing in Visual Studio 2012

I have included the following code in my master page: <link rel='stylesheet' id='layer-styles-css' href='css/layerslider.css?ver=3.4.1' type='text/css' media='all' /> When debugging in MS Vis ...

After clicking the submit button, make sure to automatically fill in all empty input fields

I am currently working on a form that includes various input types such as text fields, radio buttons, select dropdowns, and text areas. The form is displayed in a table format with an option to add additional rows. One issue I have encountered is that us ...

Should commas be used in variables?

Could this be converted in a different way? $('#id').testfunction({ 'source' : [ {'source':'pathimage.jpg','title':'Title 1','description':'This is a description 1.'}, ...

What is the best method to restrict the size of a div to match the dimensions of the

In my webpage, I have a menubar (div) that contains bookmarks. However, when too many bookmarks are added, the menu becomes too wide for the page size I prefer (1280, 720) and becomes scrollable, causing some bookmarks to be out of view. My goal is to ens ...

Updating and Deleting Interactive Features using Jquery

Seeking assistance with a coding issue. I am trying to add two dynamic text boxes to a div tag when a button is clicked. Upon subsequent clicks of the button, I want to remove the previously added text boxes and replace them with new ones. You can view my ...

Is there a way to link multiple GET requests and combine their results into an array in JavaScript/Node?

The current code is a bit messy, and I'm still unsure about the then method. What each 'get' call returns: An array with some, but not all, results. What I need: To pass two different URIs, concatenate the results of both, and then expor ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...