How can I make this more manageable? The song elements are generated by PHP so I don’t know how many there will be. The number of variables for current_song is also unknown but is the same as the song elements. Thanks…
function gid(name)
{
return document.getElementById(name);
};
function itemMonitor(obj)
{
var current_song = jwplayer().getPlaylistItem().index;
gid('nowplaying').innerHTML = 'Now Playing: <span>' + player.getPlaylist()[obj.index].title + '</span>';
if (current_song == 0) {
gid('song0').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 0) {
gid('song0').style.backgroundColor = "#ffffff";}
if (current_song == 1) {
gid('song1').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 1) {
gid('song1').style.backgroundColor = "#ffffff";}
if (current_song == 2) {
gid('song2').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 2) {
gid('song2').style.backgroundColor = "#ffffff";}
if (current_song == 3) {
gid('song3').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 3) {
gid('song3').style.backgroundColor = "#ffffff";}
if (current_song == 4) {
gid('song4').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 4) {
gid('song4').style.backgroundColor = "#ffffff";}
if (current_song == 5) {
gid('song5').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 5) {
gid('song5').style.backgroundColor = "#ffffff";}
if (current_song == 6) {
gid('song6').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 6) {
gid('song6').style.backgroundColor = "#ffffff";}
if (current_song == 7) {
gid('song7').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 7) {
gid('song7').style.backgroundColor = "#ffffff";}
if (current_song == 8) {
gid('song8').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 8) {
gid('song8').style.backgroundColor = "#ffffff";}
if (current_song == 9) {
gid('song9').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 9) {
gid('song9').style.backgroundColor = "#ffffff";}
if (current_song == 10) {
gid('song10').style.backgroundColor = "#E6E8FA";}
else if (current_song !== 10) {
gid('song10').style.backgroundColor = "#ffffff";}
};
Use the following code. All song-elements are obtained through
document.querySelectorAll('[id^="song"]'). Then, you loop through this collection, and set the desired property:Note regarding coding style:
function name(){}) do not have to be postfixed by a semicolon. It’s not illegal though.if (a === b) { ... } else if (a !== b){..}can be shortened toif (a === b) {...} else { ... }, because if a is not equal to b, then it is unequal.