Add dynamic blog preview to homepage
- Create blog/posts.json for managing blog post metadata - Add blog preview box (max 1/3 screen width) to homepage - Fetch latest post dynamically with image and excerpt - Updates automatically when new posts added to JSON - Styled to fit no-scroll homepage layout - Link to full blog page for each post
This commit is contained in:
39
script.js
39
script.js
@ -126,4 +126,41 @@ uncomment the code below.
|
||||
// <div class="heading">CSS</div>
|
||||
// <pre>${css.join("\n\n")}</pre>
|
||||
// </div>
|
||||
// `;
|
||||
// `;
|
||||
|
||||
// Load latest blog post preview
|
||||
async function loadLatestBlogPost() {
|
||||
try {
|
||||
const response = await fetch('./blog/posts.json');
|
||||
const posts = await response.json();
|
||||
|
||||
if (posts.length === 0) {
|
||||
document.getElementById('latestBlogPreview').innerHTML = '<p style="color: #9d9aa4;">No blog posts yet.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the latest post (first in the array)
|
||||
const latestPost = posts[0];
|
||||
|
||||
// Create the preview HTML
|
||||
const previewHTML = `
|
||||
<a href="./blog/#${latestPost.slug}" class="blog-preview-title">${latestPost.title}</a>
|
||||
<div class="blog-preview-date">${new Date(latestPost.date).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}</div>
|
||||
<img src="${latestPost.image}" alt="${latestPost.title}" />
|
||||
<p class="blog-preview-excerpt">${latestPost.excerpt}</p>
|
||||
<a href="./blog/#${latestPost.slug}" class="blog-preview-link">Read more →</a>
|
||||
`;
|
||||
|
||||
document.getElementById('latestBlogPreview').innerHTML = previewHTML;
|
||||
} catch (error) {
|
||||
console.error('Error loading blog posts:', error);
|
||||
document.getElementById('latestBlogPreview').innerHTML = '<p style="color: #9d9aa4;">Error loading blog posts.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// Load blog preview when page is ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', loadLatestBlogPost);
|
||||
} else {
|
||||
loadLatestBlogPost();
|
||||
}
|
||||
Reference in New Issue
Block a user