Web/scripts/blog.js
Ell 7470a20886
All checks were successful
Web/pipeline/head This commit looks good
made the blog category a search string
2021-03-31 17:00:15 +02:00

72 lines
2.5 KiB
JavaScript

$("#blog-archive-button").on("click", function () {
let archive = $('#blog-archive');
archive.toggle();
$(this).html((archive.is(":visible") ? "Hide" : "Show") + " archived posts");
});
$.ajax({
dataType: "json",
url: "blog/src/posts.json",
cache: false,
success: function (json) {
let category = "Featured";
let match = window.location.search.match(/cat=([^&]+)/);
if (match) {
let cat = decodeURI(match[1]);
if (json.some(p => p.cat.includes(cat)))
category = cat;
}
populateBlog(json, category);
forceToAnchor();
}
});
function populateBlog(json, currCat) {
let archive = $('#blog-archive');
let list = $('#blog-list');
let cats = $('#blog-cats');
archive.html("");
list.html("");
cats.html("");
// force all and featured categories to be first
addCatButton(json, cats, "All Posts", currCat);
addCatButton(json, cats, "Featured", currCat);
for (let i = json.length - 1; i >= 0; i--) {
let post = json[i];
for (let cat of post.cat)
addCatButton(json, cats, cat, currCat);
if (currCat === "All Posts" || post.cat.includes(currCat)) {
let p = /*html*/ `
<div class="card bg-light blog-entry rounded-0">
<div class="card-body">
<h4 class="card-title blog-title"><a class="blog-button" href="./blog/${post.id}">${post.name}</a></h4>
<div class="card-text blog-summary">${post.summary}</div>
<span class="text-muted project-status">${post.date}</span>
<span class="text-muted blog-cat">${post.cat.join(", ")}</span>
</div>
</div>
`;
if (post.archived) {
archive.append(p);
} else {
list.append(p);
}
}
}
if (!archive.html())
archive.html(`<em>There are no archived ${currCat} posts.</em>`);
}
function addCatButton(json, cats, cat, currCat) {
let catAnchor = `blog-cat-${cat.toLowerCase().replace(" ", "_")}`;
if (!$(`#${catAnchor}`).length) {
cats.append( /*html*/ `<button type="button" class="btn btn-link blog-cat-button" id=${catAnchor} ${cat === currCat ? "disabled" : ""}>${cat}</button>`);
$(`#${catAnchor}`).on('click', function () {
populateBlog(json, cat);
history.replaceState(null, null, `?cat=${cat}${location.hash}`);
});
}
}