-3

I am trying to localStore the history but it does not work. I tried JSON.stringify and a script called JStorage but I couldn't get either to work.

function updateHistory(video) {
getHistory();
blacklist[video["id"]] = true;
myhistory.push(video);
var html = "<li class=\"history\">" +
    "<img class= \"img-rounded\" src=\"{0}\"/>" +
    "<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
    "by {3}<br>" +
    "{4} | {5} views</p>" +
    "</li>";

$("#myhistory").prepend(html.format(video["thumbnail"],
    video["id"],
    video["title"],
    video["uploader"],
    video["length"],
    video["views"]));
saveHistory();
}

function saveHistory() {
localStorage.setItem(myhistory, myhistory.innerHTML);
}

(The alert does show up)

function getHistory() {
localStorage.getItem(myhistory);
alert("working");
}
bohmygod
  • 31
  • 1
  • 9

1 Answers1

0

The point is, instead of storing the html part you better store the video object instead, you can store videos based on their id, and instead of array use javascript object:

function setVideo(video) {
    var videos = JSON.parse(localStorage.getItem("myhistory") || "{}");
    videos[video["id"]]=video;
    localStorage.setItem("myhistory", JSON.stringify(videos));
}
function getVideos() {
    var myhistory = localStorage.getItem("myhistory");
    if(!myhistory) return {};
    else return JSON.parse(myhistory);
}
function getVideo(id) {
    var myhistory = localStorage.getItem("myhistory");
    if(!myhistory) return null;
    var videos = JSON.parse(myhistory);
    return videos[id] || null;
}

now you can use getVideo to retrieve the video object by id.you can separate the part which shows the video, like:

function showVideo(video) {
    blacklist[video["id"]] = true;
    var html = "<li class=\"history\">" +
        "<img class= \"img-rounded\" src=\"{0}\"/>" +
        "<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
        "by {3}<br>" +
        "{4} | {5} views</p>" +
        "</li>";

    $("#myhistory").prepend(html.format(video["thumbnail"],
    video["id"],
    video["title"],
    video["uploader"],
    video["length"],
    video["views"]));
}

let's say you want to show the whole videos in the history:

var videos = getVideos();
for(var id in videos){
    showVideo(videos[id]);
}
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • Thanks, but how would I use getVideo to make the video show up in the array next time the user uses the site? – bohmygod Feb 20 '14 at 19:56