/* Display this image by default, and reveal the monster behind it after it’s clicked. People who navigate the web with a keyboard or use a screen reader should still be able to play this game. */
const render = function () { app.innerHTML = '<p>Click a door to reveal a monster. Try not to find the sock.</p><div class="row">' + monsters.map(monster => { return (` <div class="grid" aria-live="polite"><button class="show_button" data-id="${monster}"><img alt= "Click this picture of door to see monster" src="../img/door.svg"/></button></div> `) }).join('') + '</div>'; };
const shuffleArr = function (arr) { var currentIndex = arr.length; var temporaryValue, randomIndex;
/* In today’s project, we’re going to modify our API cache script to fallback to the cache if the API call fails—even if data has expired. Showing something, even if it’s a bit out of date, is better than showing nothing at all.*/
const appOutput = document.querySelector('#app'); let storageID; var numberOfArticles = 2; const sanitizeHTML = function (str) { return str.replace(/[^\w. ]/gi, function (c) { return'&#' + c.charCodeAt(0) + ';'; }) }; const isDataValid = function (saved, expirationDate) { if (!saved || !saved.data || !saved.timestamp) returnfalse; const difference = newDate().getTime() - saved.timestamp; return difference < expirationDate; } const saveData = function (data) { const cache = { data: data, timestamp: newDate().getTime() } localStorage.setItem(storageID, JSON.stringify(cache)); } const getData = function () { const saved = JSON.parse(localStorage.getItem(storageID)); if (!saved) return; if (isDataValid(saved, 1000 * 10)) { return saved.data; } } const render = function (articles) { appOutput.innerHTML = '<h3 class="category">Pirate articles:</h3>' + articles.map(function (article) { return (` <div class="container"> <ul class="title"> <li> <strong>Title:</strong> ${sanitizeHTML(article.title)}</li> <li> <strong>Author:</strong> ${sanitizeHTML(article.author)}</li> <li> <strong>Publication date:</strong> ${sanitizeHTML(article.pubdate)}</li> </ul> <div class="article"><p>${sanitizeHTML(article.article)}</p></div> </div> <hr> <br> `); }).join(''); } const getFirstFewArticles = function (articles) { return articles.slice(0, numberOfArticles); } const getNews = function () { // Check for valid cached data, // If exist, use it const saved = getData(); if (saved) { render(saved); console.log("Loaded from cache"); return; } fetch('https://vanillajsacademy.com/api/pirates.json').then(function (response) { if (response.ok) { return response.json(); } else { returnPromise.reject(response); } }).then(function (data) { const articles = getFirstFewArticles(data.articles); saveData(articles); render(articles); console.log("Fetched from API"); }).catch(function (error) { console.log("something went wrong", error); appOutput.textContent = "Something went wrong..."; }) } getNews();