WebsiteTemplate/blog/js/blog.js
2026-01-25 11:33:37 -04:00

62 lines
2.4 KiB
JavaScript

// Summon the blog posts from their JSON tomb
async function loadBlogPosts() {
try {
// Use relative path - this should work when blog.js is loaded from /blog/index.html
const apiPath = 'api/posts.php';
const response = await fetch(apiPath);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const posts = await response.json();
// Validate that we got an array
if (!Array.isArray(posts)) {
throw new Error('Invalid response format: expected array');
}
const container = document.getElementById("blogPostsContainer");
if (!container) {
throw new Error('Blog posts container not found');
}
// Newest first - we're not savages reading in chronological order
const sortedPosts = posts.sort((a, b) => new Date(b.date) - new Date(a.date));
// Out with the old (loading message probably)
container.innerHTML = '';
if (sortedPosts.length === 0) {
container.innerHTML = '<p class="error">No blog posts found. Add some posts to get started!</p>';
return;
}
sortedPosts.forEach(post => {
const postElement = document.createElement('div');
postElement.className = 'blog-post-preview';
postElement.id = `post-preview-${post.id}`;
postElement.innerHTML = `
<h2 class="blog-post-title"><a href="post.html?id=${post.id}" class="blog-post-link">${post.title}</a></h2>
<p class="blog-post-date">${post.date}</p>
<p class="blog-post-excerpt">${post.excerpt}</p>
<a href="post.html?id=${post.id}" class="blog-read-more">Read more →</a>
`;
container.appendChild(postElement);
});
} catch (error) {
console.error('Error loading blog posts:', error);
const container = document.getElementById("blogPostsContainer");
if (container) {
container.innerHTML =
'<p class="error">Error loading blog posts. Make sure you\'re running a PHP server and the posts.json file exists.</p>';
}
// Fail gracefully - no one likes a drama queen
}
}
// Start the blog parade when the page finishes loading
window.addEventListener('load', loadBlogPosts);