inserting a for-loop inside a div tag

I've created a script that modifies the background color and plays a sound in response to user input. The changes are triggered by the length of the input provided. Additionally, I have a div element where I aim to display the specific letter causing the change, iterating through each letter from the for-loop. Therefore, as the colors change, so should the content within the div, showing each individual letter sequentially - like when the user enters "hello", it should transition from h to e, then l, and so on. Currently, my implementation only displays the length of the input, so any help or guidance would be greatly appreciated.

document.getElementById('icard').innerHTML = i;

Check out the jsBin example here

Answer №1

list3 holds the collection of characters you are working with. To access a specific character during each iteration of the loop, do the following:

 document.getElementById('icard').innerHTML = list3[i];

Answer №2

Here is the updated version of your code with the necessary fixes applied. Enjoy coding!

  <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    body{background:#ccc;}
    </style>
</head>

<body>  

        <form name="name1" method="post" id="name1">
        <select class="select1" id="selectid" name="selectuser" onChange='Choice();'>
        <option>Your text</option>
        <option value="1">English</option>
        <option value="2">French</option>
        <option value="3">German</option>
        <option value="4">Turkish</option>
        <option value="5">Slovak</option>
        <option value="6">Spanish</option>
        </select>
        <input class="input1" id="ids" name="id" onkeyup="getVal()" type="text"  o>
        <input type="button" value="Submit" name="B1" onclick="getText()">
        </form>  

    <div id="icard" class="drag" style="left: 0px; top: 0px; width:10%;  height:10%;"></div>
    <audio id="audio">
    <source src='http://www.mediacollege.com/downloads/sound-effects/hit/hit-01.wav' type="audio/mpeg" />
    </audio>
    <audio id="audio2">
    <source src='http://www.mediacollege.com/downloads/sound-effects/hit/hit-pipe.wav' type="audio/mpeg" />
    </audio>



    <script language="JavaScript">

    function getText() {
    var myString = document.name1.ids.value.toLowerCase();
    var list3 = myString.split('')
    var list1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
    var list2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', "ı", 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];


    for (var i = 0; i < list3.length; i++) {

       setTimeout(playOne.bind(null, list3[i]), i*550,j=i);
        //document.getElementById('icard').innerHTML = i;
        //document.body.style.backgroundColor = '#' + //Math.random().toString(16).slice(2, 8);


    }

    function playOne(entry,j) {

        if (list1.indexOf(entry) >= 0) {
           setTimeout(audio.play(null, list1[i]), i*550);
            document.getElementById('icard').innerHTML = j+1;
            document.body.style.backgroundColor = '#' + Math.random().toString(16).slice(2, 8);


        } else if (list2.indexOf(entry) >= 0) {
           setTimeout(audio2.play(null, list2[i]), i*550);
            document.getElementById('icard').innerHTML = j+1;
            document.body.style.backgroundColor = '#' + Math.random().toString(16).slice(2, 8);
        }
    }
}

    </script> 

    <script>
    var ids = new Array();
    ids[0] = "";
    ids[1] = "hello";
    ids[2] = "salut";
    ids[3] = "hallo";
    ids[4] = "merhaba";
    ids[5] = "ahoy";
    ids[6] = "ola";
            function Choice() {
                y = document.getElementById("selectid");
                  document.getElementById("ids").value = ids[y.selectedIndex];
             }
    </script>

    <script>
    var audio = document.getElementById('audio');
    var audio2 = document.getElementById('audio2');
    </script>
</body>
</html>

In summary, I have passed the iteration index to the function and captured it for further processing.

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

Ajax-powered Datatables

I am a beginner to data tables and I am attempting to retrieve data from a JSON text file (test1.txt). Below is an excerpt of the data present in the file, which contains over 5000 entries: [{"0":"22352442","ID":"22352442","1":"22126303","PARENT":"2212630 ...

Locate and retrieve the item that appears most often in a given array

In order to determine the mode of an array consisting of integer numbers only, I must create a function named findMode. If the array is empty, the function should return 0. Otherwise, it should return the element that occurs most frequently in the array. I ...

"During the testing phase, the req.body object is found

I'm currently performing unit testing on my express application using Mocha and Chai. However, when I attempt to use req.body in the test file to parse the object, I only receive undefined in the testing results. In my server (app.js), I have alread ...

What is the most effective method for inputting a date/time into a Django view?

Looking to create a feature where users can see what events are happening at a specific time. What is the most efficient method to implement this request? For example, if I want to display all current events, should I submit a post request to /events/2009 ...

ElementUI Cascader not rendering properly

Utilizing elementUI's cascading selector to present data, I have crafted this code in accordance with the official documentation. <el-cascader v-model="address" :options="addressOptions" :props="{expandTrigger: 'hover'}" ...

Issues with non-functional plugins that utilize AJAX functionality

I am encountering an issue with my code that includes an ajax script for deleting a record, along with an animation during the deletion process. However, when I try to integrate the ajax script with plugins for confirmation, it seems to not be working prop ...

What is the functionality of the protection against AngularJS JSON vulnerability?

When working with JSONs in Angular, it is recommended to prefix them with )]}'\n for added protection against potential JSON vulnerability: A JSON vulnerability could allow a third-party website to transform your JSON resource URL into a JSONP ...

Implementing event dispatch on Push notifications received with Workbox

In my VueJS component, I have set up a listener for the pushMessageEvent event: <template> <div> <VueBotUI :options="options" :is-open="isOpen" :bot-typing="botTyping" :inpu ...

AngularJS Service failing to appear on screen

I am trying to access my Github information using Github's API. I can see the correct information when I log my http request, but for some reason it is not showing up on the page. There are no errors being thrown, but the requested data is not display ...

I encountered login issues when trying to access dist/index.html in my Angular 8 application, but I found a workaround by utilizing the proxy.conf.json file, which

I have been trying to login through the index.html page in the angular 8 dist folder, but I keep encountering an error with the login API URL. Despite spending two days on this issue, I have not been able to find a solution. If anyone has any suggestions o ...

Tips for toggling the visibility of a <div> element with a click event, even when there is already a click event assigned

No matter what I try, nothing seems to be working for me. I'm looking to hide the <div id="disqus_thread"> at first and then reveal it when I click on the link "commenting", after the comments have loaded. This particular link is located at the ...

Sorting through a list post a retrieval action

Could you guys please help me understand why my code is not functioning properly? I am receiving an array from my backend rails API, which is providing the data correctly. I have created an empty array where I filter the records based on their ID. The fi ...

What could be the reason for my React/HTML select element occasionally failing to display the default selected value?

I am currently working on creating a select element in Reactjs/HTML and I am facing an issue with setting a default value based on a component variable. Essentially, the default value of the select should be the id of a component. This is my current imple ...

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

What is the best method for efficiently loading SVG icons on an HTML page without redundancy? / Is utilizing <use href> recommended?

My struggle with implementing icons in Angular While working on a new Angular project, I've encountered challenges with my current SVG-icon implementation method from a previous project (@ngneat/svg-icon). The process involves organizing SVG files in ...

How can we create a two-dimensional image with random dimensions using Math.random?

I am struggling to create a variety of flowers with different sizes from an Array. The issue I'm facing is that every time I click to add a new flower, it changes the size of all existing flowers as well. What I would like is for each added flower to ...

Display a JavaScript variable as an attribute within an HTML tag

let disableFlag = ''; if(value.action.length === 0) { disableFlag = 'disabled="disabled"'; } row += '<td><input type="checkbox" name="create" value="1" class="checkbox" data-action="'+ value.action + '" data-co ...

Highlighting an Element Using Selenium Webdriver at Specific Coordinates

I'm currently in the process of automating a web application built with HTML5 using Selenium Webdriver. I need help figuring out how to highlight the exact coordinates where I have clicked on the Canvas element. For example, if I click on the Canvas a ...

The issue with ui-router failing to render the template in MVC5

I'm having trouble setting up a basic Angular UI-Router configuration. My goal right now is to have a hardcoded template render properly, and then work on loading an external .html file. My project is using MVC5, so I'll provide the necessary fi ...

Difficulty with Vue Router horizontal scrolling to hash functionality

My goal is to achieve horizontal scrolling of the viewport by using a button wrapped in a router-link that navigates to a vue component. I was successful in achieving this functionality using anchor tags: <a href="#about"> <button cl ...