|
| 1 | +// View Counter for Blog Posts |
| 2 | +// Tracks page views and stores them in localStorage |
| 3 | + |
| 4 | +class ViewCounter { |
| 5 | + constructor() { |
| 6 | + this.storageKey = 'blog_view_counts'; |
| 7 | + this.currentPost = this.getCurrentPostSlug(); |
| 8 | + this.init(); |
| 9 | + } |
| 10 | + |
| 11 | + getCurrentPostSlug() { |
| 12 | + // Extract post slug from URL |
| 13 | + const path = window.location.pathname; |
| 14 | + const match = path.match(/\/blog\/(\d{4}-\d{2}-\d{2}-[^\/]+)/); |
| 15 | + return match ? match[1] : null; |
| 16 | + } |
| 17 | + |
| 18 | + init() { |
| 19 | + if (this.currentPost) { |
| 20 | + this.incrementViewCount(); |
| 21 | + this.updateViewDisplay(); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + getViewCounts() { |
| 26 | + try { |
| 27 | + const stored = localStorage.getItem(this.storageKey); |
| 28 | + return stored ? JSON.parse(stored) : {}; |
| 29 | + } catch (e) { |
| 30 | + console.warn('Could not load view counts from localStorage:', e); |
| 31 | + return {}; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + setViewCounts(counts) { |
| 36 | + try { |
| 37 | + localStorage.setItem(this.storageKey, JSON.stringify(counts)); |
| 38 | + } catch (e) { |
| 39 | + console.warn('Could not save view counts to localStorage:', e); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + incrementViewCount() { |
| 44 | + const counts = this.getViewCounts(); |
| 45 | + counts[this.currentPost] = (counts[this.currentPost] || 0) + 1; |
| 46 | + this.setViewCounts(counts); |
| 47 | + } |
| 48 | + |
| 49 | + getViewCount(postSlug) { |
| 50 | + const counts = this.getViewCounts(); |
| 51 | + return counts[postSlug] || 0; |
| 52 | + } |
| 53 | + |
| 54 | + updateViewDisplay() { |
| 55 | + const viewCount = this.getViewCount(this.currentPost); |
| 56 | + const viewElement = document.getElementById('view-counter'); |
| 57 | + if (viewElement) { |
| 58 | + viewElement.textContent = `${viewCount} view${viewCount !== 1 ? 's' : ''}`; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Method to get all view counts for blog listing |
| 63 | + getAllViewCounts() { |
| 64 | + return this.getViewCounts(); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +// Initialize view counter when DOM is loaded |
| 69 | +document.addEventListener('DOMContentLoaded', function() { |
| 70 | + window.viewCounter = new ViewCounter(); |
| 71 | +}); |
| 72 | + |
| 73 | +// Export for use in other scripts |
| 74 | +if (typeof module !== 'undefined' && module.exports) { |
| 75 | + module.exports = ViewCounter; |
| 76 | +} |
0 commit comments