From 9f82f07ab2ed6f59be2b00a766938f2bd3eb88b2 Mon Sep 17 00:00:00 2001 From: Matt Huntington Date: Sun, 25 Dec 2022 20:28:33 -0500 Subject: [PATCH] infinite scroll --- public/app.css | 7 ++++++- public/app.js | 20 ++++++++++++++++++++ public/index.html | 11 +++++++++++ server.js | 17 +++++++++++------ views/all.ejs | 23 ----------------------- 5 files changed, 48 insertions(+), 30 deletions(-) create mode 100644 public/index.html delete mode 100644 views/all.ejs diff --git a/public/app.css b/public/app.css index c975677..9c53220 100644 --- a/public/app.css +++ b/public/app.css @@ -1,7 +1,12 @@ +body { + margin:0px; +} li { + display:inline-block; border:1px solid black; list-style:none; } ul { - padding:0 + padding:0; + margin:0; } diff --git a/public/app.js b/public/app.js index e69de29..b491d0a 100644 --- a/public/app.js +++ b/public/app.js @@ -0,0 +1,20 @@ +let next; +const handleData = (data)=>{ + if(data.posts.length > 0){ + for(post of data.posts){ + const li = document.createElement('li'); + li.innerHTML = `` + document.querySelector('ul').appendChild(li) + next = data.next + } + } +} + +window.addEventListener('DOMContentLoaded', (event) => { + fetch('/posts').then(response => response.json()).then(handleData); +}); +document.addEventListener('scroll', (event)=>{ + if(document.querySelector('body').scrollHeight == window.scrollY+window.innerHeight){ + fetch('/posts/after/'+next).then(response => response.json()).then(handleData); + } +}) diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..26498d6 --- /dev/null +++ b/public/index.html @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/server.js b/server.js index 088f8c6..ff18ff3 100644 --- a/server.js +++ b/server.js @@ -48,20 +48,25 @@ const generate = async (req, res)=>{ const config = await getToken() const response = await axios.get(url, config) + const next = response.data.data.after; + const posts = response.data.data.children.filter(post => { + return post.data.subreddit === 'ProgrammerHumor' && post.data.removed_by_category === null + }).map(post => { + return post.data.permalink + }) - res.render('all.ejs', { - posts: response.data.data.children.filter(post => post.data.subreddit === 'ProgrammerHumor' && post.data.removed_by_category === null), - next: response.data.data.after, - previous: response.data.data.before + res.json({ + posts, + next }) } getToken(); -app.get('/', generate) +app.get('/posts/', generate) -app.get('/:direction/:page', generate) +app.get('/posts/:direction/:page', generate) app.listen(3002, ()=>{ console.log('listening'); diff --git a/views/all.ejs b/views/all.ejs deleted file mode 100644 index 004a098..0000000 --- a/views/all.ejs +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - -