From 53fe8e9a125021e64ad9e65eb5afccb527c96138 Mon Sep 17 00:00:00 2001 From: Marius Gavrilescu Date: Sun, 28 May 2017 00:10:13 +0300 Subject: [PATCH] Add a "Previous" button to the player --- player.js | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/player.js b/player.js index 0941012..7adcdd8 100644 --- a/player.js +++ b/player.js @@ -6,8 +6,9 @@ var TYPES = { "MP3": "audio/mpeg" }; -var audio, details, start, data; +var audio, details, start, prev, data; var hash_to_id = {}, inhibit_handle_hash = false; +var hist = [] function load_song (id) { audio.style.display = "inline"; @@ -34,24 +35,47 @@ function load_song (id) { function play_random () { start.innerHTML = "Next"; var id = Math.floor(Math.random() * data.length); + hist.push(id); + if(hist.length > 1) + prev.disabled = false; load_song(id); audio.play(); } -function handle_hash(){ +function play_random_after_error () { + hist.pop(); /* Purge offending song from history */ + play_random(); +} + +function play_prev () { + hist.pop(); + var song = hist[hist.length - 1]; + console.log("Will now play: " + song) + if(hist.length <= 1) + prev.disabled = true; + load_song(song); + audio.play(); +} + +function handle_hash(first_run){ if(!hash_to_id.hasOwnProperty(location.hash) || inhibit_handle_hash) return; - load_song(hash_to_id[location.hash]); + var id = hash_to_id[location.hash] + if(first_run === true) + hist.push(id) + load_song(id); start.innerHTML = "Next"; audio.play(); } window.onload = function () { var container = document.getElementById("player"); - container.innerHTML = '
(or click a song title)
'; + container.innerHTML = '
(or click a song title)
'; audio = document.getElementById("audio"); details = document.getElementById("details"); start = document.getElementById("start_player"); + prev = document.getElementById("prev_player") + prev.disabled = true; data = []; var trs = document.querySelectorAll("tbody tr"); @@ -77,8 +101,9 @@ window.onload = function () { audio.style.display = "none"; audio.addEventListener('ended', play_random); - audio.addEventListener('error', play_random); + audio.addEventListener('error', play_random_after_error); start.addEventListener('click', play_random); + prev.addEventListener('click', play_prev); window.onhashchange = handle_hash; - handle_hash(); + handle_hash(true); }; -- 2.39.2