Created
September 1, 2018 16:44
-
-
Save spacelatte/7b1d33b53b64db13ad46f285dc69ef67 to your computer and use it in GitHub Desktop.
single page hacker news feed with bare html and fetch api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<button onclick='load("beststories")' >best</button> | |
<button onclick='load("topstories")' >top</button> | |
<button onclick='load("newstories")' >new</button> | |
<div id=news ></div> | |
</body> | |
<script> | |
"use strict"; | |
const host = "hacker-news.firebaseio.com" | |
const target = document.querySelector("#news") | |
function story(id, callback) { | |
return fetch(`https://${host}/v0/item/${id}.json`).then(function(resp) { | |
return resp.json() | |
}).then(function(json) { | |
return callback(json) | |
}) | |
} | |
function load(type, opts) { | |
opts = { | |
max: parseInt(window.location.hash.substring(1)) || 10, | |
} | |
return fetch(`https://${host}/v0/${type}.json`).then(function(resp) { | |
return resp.json() | |
}).then(function(json) { | |
target.innerHTML = "" | |
json.forEach(function(item, index) { | |
if(index >= opts.max) { | |
return | |
} | |
return story(item, function(data) { | |
//console.table(data) | |
target.innerHTML += (` | |
<div> | |
<h2>${data.title}</h2> | |
<p>${new Date(data.time).toString()}</p> | |
<a href="${data.url || "#"}">${data.url || ""}</a> | |
<p>${data.text || ""}</p> | |
</div> | |
<hr /> | |
`) | |
return | |
}) | |
}) | |
return json | |
}) | |
} | |
window.onload = function(e) { | |
return load("topstories") | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment