Make blog page dynamic using JSON data
- Blog posts now load from blog/posts.json - Create blog/script.js to dynamically render posts - Each post displays: title, date, content, image - Support hash-based navigation to specific posts - Updated blog/index.html to load posts dynamically - Added styling for blog posts and containers - First post is 'Status' matching the original content
This commit is contained in:
53
blog/script.js
Normal file
53
blog/script.js
Normal file
@ -0,0 +1,53 @@
|
||||
"use strict";
|
||||
|
||||
// Load and display blog posts from JSON
|
||||
async function loadBlogPosts() {
|
||||
try {
|
||||
const response = await fetch('./posts.json');
|
||||
const posts = await response.json();
|
||||
|
||||
const blogsContainer = document.getElementById('blogsContainer');
|
||||
|
||||
if (posts.length === 0) {
|
||||
blogsContainer.innerHTML = '<div class="no-posts"><p>No blog posts yet.</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Create HTML for each post
|
||||
const postsHTML = posts.map(post => `
|
||||
<article class="blog-post" id="${post.slug}">
|
||||
<h2 class="blog-post-title">${post.title}</h2>
|
||||
<div class="blog-post-date">${new Date(post.date).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}</div>
|
||||
<div class="blog-post-content">
|
||||
${post.content}
|
||||
</div>
|
||||
<div class="blog-post-image">
|
||||
<img src="${post.image}" alt="${post.title}" />
|
||||
</div>
|
||||
</article>
|
||||
`).join('');
|
||||
|
||||
blogsContainer.innerHTML = postsHTML;
|
||||
} catch (error) {
|
||||
console.error('Error loading blog posts:', error);
|
||||
document.getElementById('blogsContainer').innerHTML = '<div class="error"><p>Error loading blog posts.</p></div>';
|
||||
}
|
||||
}
|
||||
|
||||
// Load blog posts when page is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', loadBlogPosts);
|
||||
} else {
|
||||
loadBlogPosts();
|
||||
}
|
||||
|
||||
// Handle hash-based navigation to specific posts
|
||||
window.addEventListener('hashchange', () => {
|
||||
const postId = window.location.hash.slice(1);
|
||||
if (postId) {
|
||||
const element = document.getElementById(postId);
|
||||
if (element) {
|
||||
element.scrollIntoView({ behavior: 'smooth' });
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user