Divs created in Javascript

Asked

Viewed 48 times

-2

I’m creating a kind of playlist (so far everything on it works as expected) and I did a detail for the selection of songs where I created for each song a div with the name of the song, and instead of creating element by element for each song in the folder I made a loop to create separate Ivs and add in another:

var musicas = ['Aqui', 'vai', 'o', 'nome', 'das', 'músicas'];
var musics = document.querySelector('.musics');
i = 0;

while(i < musicas.length) {
    var nome_musicas = document.createElement('div');
    musics.appendChild(nome_musicas);
    nome_musicas.classList.add('name');
    nome_musicas.classList.add('music_number_' + i);
    nome_musicas.innerHTML = musicas[i];
    i++;
}

My problem now is to find a logic, when I click on the div with the song she give me the name of the song that is inside her so I can do another step to play the selected song.

2 answers

1

If I understood your doubt well enough that you create a function that receives the name of the song as parameter and in it you can develop the logic you want, it would be something like this:

function play(music) {
    console.log(music)
}

Having created the function just add in the click event of the element you want

nome_musicas.onclick = () => play(musicas[i])

your final code would look something like this:

var musicas = ['Aqui', 'vai', 'o', 'nome', 'das', 'músicas'];
var musics = document.querySelector('.music');
i = 0;

function play(music) {
    console.log(music)
}

while(i < musicas.length) {
    var nome_musicas = document.createElement('div');
    musics.appendChild(nome_musicas);
    nome_musicas.classList.add('name');
    nome_musicas.classList.add('music_number_' + i);
    nome_musicas.innerHTML = musicas[i];
    nome_musicas.onclick = () => play(musicas[i])
    i++;
}
  • Got it! It is that in the other functions of the playlist (pass the music, return of music, leave random and auto pass the music when one is over) I used a counter that picked the position of the music in the list and passed to tag audio play. My idea in this creation of Divs to be the list of songs was that when I clicked on a div she gave me the name of the song inside her and I check in which position of the 'songs' he is in the variable and pass this position to the counter for him to play the chosen song.

1

  1. In HTML the attributes data-* form a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between HTML and its representation GIFT by way of script.
  2. The method forEach() executes a callback provided once for each element of the array.
  3. The estate HTMLElement.dataset allows access, reading and writing, to all custom data attributes data-* element. The property maps a DOMString each custom data attribute.

const songs = ['Aqui', 'vai', 'o', 'nome', 'das', 'músicas'];
const soundtracks = document.querySelector('.soundtracks');

//Para cada elemento da array songs onde val é o elemento e idx seu índice na array
songs.forEach(function(val, idx) {
  const btn = document.createElement('button');     //Usei botões pois achei que são semanticamente mais adequados a seletores de música, mas poderia ser usado um div com ARIA: button role para tecnologia assistiva.
  btn.classList.add('name');
  btn.dataset.number = idx;                        //Salva no atributo data-number o índice da música.
  btn.innerText = val;                             //Ajusta o texto do botão para o nome da música.
  //Adiciona o evento click ao botão
  btn.addEventListener("click", function(e) {
    console.log(`Tocando agora: ${songs[e.target.dataset.number]}`);
  });
  soundtracks.append(btn);
});
.soundtracks {
  display: grid;
}

.soundtracks button {
  text-align: left;
  border: none;
  background: none;
}

.soundtracks button:hover {
  background: navy;
  color: gold;
}
<div class="soundtracks">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.