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

The issue with Bootstrap Vue is that it fails to render the CSS properly when utilizing cards

Recently, I delved into the world of Bootstrap Vue and wrote the code snippet below: <template> <div> <div> <b-card-group> <b-card border-variant="dark" header="Dark" align="center"> &l ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

Assistance needed with CSS floating properties

Despite seeing many inquiries about float, I still can't pinpoint what's causing my issue. My objective is simple: GREETINGS FRIEND I aim for it to align just to the left of the unordered list. Referencing this solution, I attempted adding cl ...

Recording web browser network traffic using JavaScript

Is there a method in webdriverio that allows me to capture and validate the response of API calls made by the browser while loading data for my automated tests? ...

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

I am looking for assistance constructing a task management application using vue.js

I am facing an issue with developing a to-do list using Vue.js. The goal is to add tasks to the list by entering them and clicking a button. Once added, the new task should show up under "All Tasks" and "Not finished". Buttons for marking tasks as " ...

Locate a JQuery element within another JQuery element

Apologies for my poor grasp of English. I am working with HTML and JavaScript. <noindex> <h1>This is h1 in noindex</h1> <div> <h1>This is h1 in noindex and in div</h1> <div> <h1>This is h1 in noindex a ...

Exploring XPath: strategies for excluding text within nested elements

if I come across some HTML structure like this: <div class=unique_id> <h1 class="parseasinTitle"> <span> Game Title </span> </h1> Game Developer </div> Is there a unique way to extract only the "Game Develo ...

Consistent user interface experience for both Electron and browser users

Can the same index.html file be used by both an Electron process and a browser like Chrome? I have created an app that has its own Hapi server to handle HTTP requests to a database, which is working fine. However, when I try to serve the index.html file f ...

There seems to be a column in the MySQL INSERT query that is unidentifiable and does not exist in the list of fields

id and cost are required as integers and cannot be left empty. I encountered the following error message: 'Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'' var sql = "INSERT INTO Paintings(` ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

Implementing a feature that ensures html elements are transparent in a PDF conversion

I am in the process of converting a webpage into a format that is easily printable as a PDF, while ensuring that it maintains the same appearance. Many tools for printing to PDF do not support background images or colors, so I am attempting to overcome thi ...

Finding the correct path for ts-loader with webpack version 2.2.1 within a script

When running the gulp task below, I encounter an error: Module not found: Error: Can't resolve 'app.ts' in 'wwwroot/js/admin' gulp.task("admin:js", function (done) { module.exports = { context: "wwwroot/js/admin", ...

What could be causing the unexpected behavior in my NgMessages form validation?

I have developed a code that incorporates Angular JS form validation methods. There are two separate forms within the codebase, The initial form utilizes basic form validation while the second form employs ng-messages, However, an issue has arisen wher ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...

What are the potential ways in which an html IMG tag can disrupt the functionality of this

For years, I have been using this form code without any issues. The code functions perfectly and all the tags are correct. However, whenever I include an image tag, it displays a failure message and prevents the mail function in PHP from working. The hea ...

What is the best way to extract the text from the first visible `<td></td>` table row using jQuery?

In this particular scenario, there is a table included: <table id="table"> <thead> <tr> <th>Name</th> <th>Course</th> </tr> </thead> <tbody> <tr style="display:none"> ...