document.addEventListener('DOMContentLoaded', () => {
const galleryInner = document.querySelector('.gallery-inner');
const images = [
{ id: 'img1', url: 'https://shutranm328.macombserver.net/itwp1000/project3/images/domestictabby.jpg/250x150/FF5733/FFFFFF?text=Image+1' },
{ id: 'img2', url: 'https://via.placeholder.com/250x150/33FF57/FFFFFF?text=Image+2' },
{ id: 'img3', url: 'https://via.placeholder.com/250x150/5733FF/FFFFFF?text=Image+3' },
{ id: 'img4', url: 'https://via.placeholder.com/250x150/FFFF33/000000?text=Image+4' },
{ id: 'img5', url: 'https://via.placeholder.com/250x150/33FFFF/000000?text=Image+5' },
{ id: 'img6', url: 'https://via.placeholder.com/250x150/FF33FF/FFFFFF?text=Image+6' }
];
// Retrieve vote data from localStorage or initialize it
let votes = JSON.parse(localStorage.getItem('imageVotes')) || {};
function createGalleryItem(image) {
// Initialize vote count for the image if it doesn't exist
if (!votes[image.id]) {
votes[image.id] = 0;
}
const galleryItem = document.createElement('div');
galleryItem.className = 'gallery-item';
galleryItem.innerHTML = `
${votes[image.id]}
`;
return galleryItem;
}
// Populate the gallery
images.forEach(image => {
galleryInner.appendChild(createGalleryItem(image));
});
// Handle voting events using event delegation
galleryInner.addEventListener('click', (event) => {
const target = event.target;
if (target.classList.contains('upvote') || target.classList.contains('downvote')) {
const imageId = target.dataset.id;
if (target.classList.contains('upvote')) {
votes[imageId]++;
} else if (target.classList.contains('downvote')) {
votes[imageId]--;
}
// Update the displayed count
document.getElementById(`count-${imageId}`).textContent = votes[imageId];
// Save the updated vote counts to localStorage
localStorage.setItem('imageVotes', JSON.stringify(votes));
}
});
});