amberlist / script.js
okpala's picture
love this...
082317d verified
Raw History Blame Contribute Delete
25.8 kB
// Mock Data - Student Accommodations
const listingsData = [
{
id: 1,
title: "Vita Student Circle Square",
location: "Manchester, UK",
university: "University of Manchester",
price: 245,
originalPrice: 280,
rating: 4.9,
reviews: 128,
image: "https://images.unsplash.com/photo-1555854877-bab0e564b8d5?w=800&h=600&fit=crop",
badges: ["Bestseller", "Verified"],
amenities: ["Gym", "Cinema", "Study Room", "Roof Terrace"],
roomType: "Studio",
available: "Sep 2024",
featured: true,
coordinates: { lat: 53.4808, lng: -2.2426 }
},
{
id: 2,
title: "Student Castle Cambridge",
location: "Cambridge, UK",
university: "University of Cambridge",
price: 320,
originalPrice: 350,
rating: 4.8,
reviews: 96,
image: "https://images.unsplash.com/photo-1596276026589-276f90a9772d?w=800&h=600&fit=crop",
badges: ["Premium", "New"],
amenities: ["Pool", "Gym", "Game Room", "Laundry"],
roomType: "Ensuite",
available: "Oct 2024",
featured: true,
coordinates: { lat: 52.2053, lng: 0.1218 }
},
{
id: 3,
title: "IQ Shoreditch London",
location: "London, UK",
university: "UCL / LSE",
price: 425,
originalPrice: 475,
rating: 4.7,
reviews: 203,
image: "https://images.unsplash.com/photo-1522708323590-d24dbb6b0267?w=800&h=600&fit=crop",
badges: ["Trending", "Verified"],
amenities: ["Sky Lounge", "Gym", "Cinema", "BBQ Area"],
roomType: "Studio",
available: "Sep 2024",
featured: true,
coordinates: { lat: 51.5074, lng: -0.1278 }
},
{
id: 4,
title: "Canvas Wembley",
location: "London, UK",
university: "University of Westminster",
price: 295,
originalPrice: 320,
rating: 4.6,
reviews: 87,
image: "https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?w=800&h=600&fit=crop",
badges: ["Great Value"],
amenities: ["Gym", "Study Spaces", "Rooftop", "Events"],
roomType: "Ensuite",
available: "Sep 2024",
featured: false,
coordinates: { lat: 51.556, lng: -0.279 }
},
{
id: 5,
title: "Yugo Explore Glasgow",
location: "Glasgow, UK",
university: "University of Glasgow",
price: 185,
originalPrice: 210,
rating: 4.8,
reviews: 156,
image: "https://images.unsplash.com/photo-1493809842364-78817add7ffb?w=800&h=600&fit=crop",
badges: ["Popular", "Verified"],
amenities: ["Gym", "Cinema", "Game Room", "Laundry"],
roomType: "Studio",
available: "Aug 2024",
featured: true,
coordinates: { lat: 55.8609, lng: -4.2514 }
},
{
id: 6,
title: "Unilife Highfield",
location: "Southampton, UK",
university: "University of Southampton",
price: 165,
originalPrice: 185,
rating: 4.5,
reviews: 72,
image: "https://images.unsplash.com/photo-1501183638710-841dd1904471?w=800&h=600&fit=crop",
badges: ["Affordable"],
amenities: ["Study Room", "Common Area", "Bike Storage", "WiFi"],
roomType: "Ensuite",
available: "Sep 2024",
featured: false,
coordinates: { lat: 50.9097, lng: -1.4044 }
},
{
id: 7,
title: "Collegiate Nova",
location: "Nottingham, UK",
university: "University of Nottingham",
price: 195,
originalPrice: 225,
rating: 4.7,
reviews: 98,
image: "https://images.unsplash.com/photo-1484154218962-a1c002085d2f?w=800&h=600&fit=crop",
badges: ["New", "Verified"],
amenities: ["Gym", "Spa", "Cinema", "Rooftop Terrace"],
roomType: "Studio",
available: "Oct 2024",
featured: true,
coordinates: { lat: 52.9548, lng: -1.1581 }
},
{
id: 8,
title: "The Hive Birmingham",
location: "Birmingham, UK",
university: "University of Birmingham",
price: 175,
originalPrice: 200,
rating: 4.6,
reviews: 115,
image: "https://images.unsplash.com/photo-1502672023488-70e25813eb80?w=800&h=600&fit=crop",
badges: ["Great Value"],
amenities: ["Gym", "Study Spaces", "Social Hub", "Laundry"],
roomType: "Ensuite",
available: "Sep 2024",
featured: false,
coordinates: { lat: 52.4862, lng: -1.8904 }
},
{
id: 9,
title: "Scape Shoreditch",
location: "London, UK",
university: "Queen Mary University",
price: 385,
originalPrice: 420,
rating: 4.8,
reviews: 178,
image: "https://images.unsplash.com/photo-1522708323590-d24dbb6b0267?w=800&h=600&fit=crop",
badges: ["Premium", "Verified"],
amenities: ["Gym", "Cinema", "Rooftop Pool", "Events Program"],
roomType: "Studio",
available: "Sep 2024",
featured: true,
coordinates: { lat: 51.5203, lng: -0.0297 }
},
{
id: 10,
title: "Student Roost The Railyard",
location: "Liverpool, UK",
university: "University of Liverpool",
price: 155,
originalPrice: 175,
rating: 4.5,
reviews: 89,
image: "https://images.unsplash.com/photo-1493663284031-b7e3aefcae8e?w=800&h=600&fit=crop",
badges: ["Affordable"],
amenities: ["Common Room", "Study Area", "Bike Storage", "WiFi"],
roomType: "Ensuite",
available: "Sep 2024",
featured: false,
coordinates: { lat: 53.4084, lng: -2.9916 }
},
{
id: 11,
title: "Downing Students The Lyra",
location: "London, UK",
university: "Imperial College London",
price: 445,
originalPrice: 495,
rating: 4.9,
reviews: 234,
image: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=800&h=600&fit=crop",
badges: ["Luxury", "Premium"],
amenities: ["Gym", "Spa", "Private Cinema", "Concierge", "Rooftop Terrace"],
roomType: "Studio",
available: "Sep 2024",
featured: true,
coordinates: { lat: 51.4988, lng: -0.1749 }
},
{
id: 12,
title: "iQ Leeds",
location: "Leeds, UK",
university: "University of Leeds",
price: 165,
originalPrice: 185,
rating: 4.6,
reviews: 134,
image: "https://images.unsplash.com/photo-1505691938895-1758d7feb511?w=800&h=600&fit=crop",
badges: ["Great Value", "Verified"],
amenities: ["Gym", "Study Rooms", "Social Spaces", "Laundry"],
roomType: "Ensuite",
available: "Sep 2024",
featured: false,
coordinates: { lat: 53.808, lng: -1.553 }
}
];
// State Management
let currentListings = [...listingsData];
let filteredListings = [...listingsData];
let currentView = 'grid';
let currentSort = 'recommended';
let favorites = new Set();
let isDarkMode = false;
// DOM Elements
const listingsGrid = document.getElementById('listingsGrid');
const listingsScrollContainer = document.getElementById('listingsScrollContainer');
const searchInput = document.getElementById('searchInput');
const priceFilter = document.getElementById('priceFilter');
const searchBtn = document.getElementById('searchBtn');
const sortSelect = document.getElementById('sortSelect');
const gridViewBtn = document.getElementById('gridViewBtn');
const listViewBtn = document.getElementById('listViewBtn');
const scrollLeftBtn = document.getElementById('scrollLeftBtn');
const scrollRightBtn = document.getElementById('scrollRightBtn');
const listingCount = document.getElementById('listingCount');
const emptyState = document.getElementById('emptyState');
const clearFiltersBtn = document.getElementById('clearFiltersBtn');
const loadMoreBtn = document.getElementById('loadMoreBtn');
const quickFilters = document.querySelectorAll('.quick-filter');
// Initialize
document.addEventListener('DOMContentLoaded', () => {
loadFavorites();
checkDarkMode();
renderListings();
setupEventListeners();
updateListingCount();
feather.replace();
});
// Event Listeners
function setupEventListeners() {
// Search
searchInput.addEventListener('input', debounce(handleSearch, 300));
searchBtn.addEventListener('click', handleSearch);
// Filters
priceFilter.addEventListener('change', handleSearch);
sortSelect.addEventListener('change', handleSort);
// View Toggle
gridViewBtn.addEventListener('click', () => setView('grid'));
listViewBtn.addEventListener('click', () => setView('list'));
// Scroll Navigation
scrollLeftBtn.addEventListener('click', () => scrollListings('left'));
scrollRightBtn.addEventListener('click', () => scrollListings('right'));
// Clear Filters
clearFiltersBtn.addEventListener('click', clearAllFilters);
// Load More
loadMoreBtn.addEventListener('click', loadMoreListings);
// Quick Filters
quickFilters.forEach(btn => {
btn.addEventListener('click', () => {
searchInput.value = btn.dataset.filter;
handleSearch();
});
});
// Scroll detection for navigation buttons
listingsScrollContainer.addEventListener('scroll', updateScrollButtons);
}
// Search & Filter Logic
function handleSearch() {
const query = searchInput.value.toLowerCase().trim();
const priceRange = priceFilter.value;
filteredListings = listingsData.filter(listing => {
// Text search
const matchesSearch = !query ||
listing.title.toLowerCase().includes(query) ||
listing.location.toLowerCase().includes(query) ||
listing.university.toLowerCase().includes(query) ||
listing.roomType.toLowerCase().includes(query) ||
listing.amenities.some(a => a.toLowerCase().includes(query));
// Price filter
let matchesPrice = true;
if (priceRange) {
const [min, max] = priceRange.split('-').map(v => v === '1200+' ? Infinity : parseInt(v));
matchesPrice = listing.price >= min && (max === Infinity ? listing.price >= 1200 : listing.price <= max);
}
return matchesSearch && matchesPrice;
});
// Apply current sort
applySort();
// Update UI
renderListings();
updateListingCount();
updateEmptyState();
}
function handleSort() {
currentSort = sortSelect.value;
applySort();
renderListings();
}
function applySort() {
const sortFunctions = {
'recommended': (a, b) => (b.featured ? 1 : 0) - (a.featured ? 1 : 0) || b.rating - a.rating,
'price-low': (a, b) => a.price - b.price,
'price-high': (a, b) => b.price - a.price,
'rating': (a, b) => b.rating - a.rating,
'newest': (a, b) => b.id - a.id
};
filteredListings.sort(sortFunctions[currentSort] || sortFunctions['recommended']);
}
// View Management
function setView(view) {
currentView = view;
// Update button states
if (view === 'grid') {
gridViewBtn.classList.add('bg-white', 'dark:bg-slate-700', 'text-primary-600', 'dark:text-primary-400', 'shadow-sm');
gridViewBtn.classList.remove('text-slate-500', 'dark:text-slate-400');
listViewBtn.classList.remove('bg-white', 'dark:bg-slate-700', 'text-primary-600', 'dark:text-primary-400', 'shadow-sm');
listViewBtn.classList.add('text-slate-500', 'dark:text-slate-400');
listingsGrid.classList.remove('flex-col');
listingsGrid.classList.add('flex');
} else {
listViewBtn.classList.add('bg-white', 'dark:bg-slate-700', 'text-primary-600', 'dark:text-primary-400', 'shadow-sm');
listViewBtn.classList.remove('text-slate-500', 'dark:text-slate-400');
gridViewBtn.classList.remove('bg-white', 'dark:bg-slate-700', 'text-primary-600', 'dark:text-primary-400', 'shadow-sm');
gridViewBtn.classList.add('text-slate-500', 'dark:text-slate-400');
}
renderListings();
}
// Scroll Navigation
function scrollListings(direction) {
const scrollAmount = 400;
const currentScroll = listingsScrollContainer.scrollLeft;
const targetScroll = direction === 'left'
? currentScroll - scrollAmount
: currentScroll + scrollAmount;
listingsScrollContainer.scrollTo({
left: targetScroll,
behavior: 'smooth'
});
}
function updateScrollButtons() {
const { scrollLeft, scrollWidth, clientWidth } = listingsScrollContainer;
const canScrollLeft = scrollLeft > 0;
const canScrollRight = scrollLeft < scrollWidth - clientWidth - 10;
scrollLeftBtn.style.opacity = canScrollLeft ? '1' : '0';
scrollLeftBtn.style.pointerEvents = canScrollLeft ? 'auto' : 'none';
scrollRightBtn.style.opacity = canScrollRight ? '1' : '0';
scrollRightBtn.style.pointerEvents = canScrollRight ? 'auto' : 'none';
}
// Render Listings
function renderListings() {
if (filteredListings.length === 0) {
listingsGrid.innerHTML = '';
return;
}
const cardsHTML = filteredListings.map(listing => createListingCard(listing)).join('');
listingsGrid.innerHTML = cardsHTML;
// Re-initialize feather icons
feather.replace();
// Add event listeners to new elements
document.querySelectorAll('.favorite-btn').forEach(btn => {
btn.addEventListener('click', (e) => toggleFavorite(e, parseInt(btn.dataset.id)));
});
document.querySelectorAll('.view-details-btn').forEach(btn => {
btn.addEventListener('click', () => showListingDetails(parseInt(btn.dataset.id)));
});
}
function createListingCard(listing) {
const isFavorited = favorites.has(listing.id);
const discount = listing.originalPrice ? Math.round((1 - listing.price / listing.originalPrice) * 100) : 0;
return `
<article class="snap-start w-[320px] md:w-[360px] flex-shrink-0 bg-white dark:bg-slate-800 rounded-2xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 card-hover group">
<!-- Image Section -->
<div class="relative h-56 overflow-hidden img-zoom-container">
<img
src="${listing.image}"
alt="${listing.title}"
class="w-full h-full object-cover img-zoom"
loading="lazy"
>
<!-- Badges -->
<div class="absolute top-4 left-4 flex flex-wrap gap-2">
${listing.badges.map(badge => `
<span class="px-3 py-1 text-xs font-semibold rounded-full ${
badge === 'Bestseller' ? 'bg-secondary-500 text-white' :
badge === 'Premium' ? 'bg-purple-500 text-white' :
badge === 'New' ? 'bg-green-500 text-white' :
badge === 'Verified' ? 'bg-blue-500 text-white' :
'bg-slate-800/80 text-white backdrop-blur-sm'
} badge-pulse">
${badge}
</span>
`).join('')}
</div>
<!-- Favorite Button -->
<button
class="favorite-btn absolute top-4 right-4 w-10 h-10 rounded-full bg-white/90 dark:bg-slate-800/90 backdrop-blur-sm flex items-center justify-center shadow-lg hover:scale-110 transition-all"
data-id="${listing.id}"
aria-label="${isFavorited ? 'Remove from favorites' : 'Add to favorites'}"
>
<i data-feather="heart" class="w-5 h-5 ${isFavorited ? 'fill-red-500 text-red-500' : 'text-slate-600 dark:text-slate-300'} transition-colors"></i>
</button>
<!-- Discount Badge -->
${discount > 0 ? `
<div class="absolute bottom-4 left-4 px-3 py-1 bg-red-500 text-white text-sm font-bold rounded-lg">
Save ${discount}%
</div>
` : ''}
</div>
<!-- Content Section -->
<div class="p-5">
<!-- Title & Rating -->
<div class="flex items-start justify-between gap-2 mb-2">
<h3 class="font-bold text-lg text-slate-900 dark:text-white leading-tight line-clamp-2 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
${listing.title}
</h3>
<div class="flex items-center gap-1 flex-shrink-0">
<i data-feather="star" class="w-4 h-4 fill-yellow-400 text-yellow-400"></i>
<span class="font-bold text-slate-900 dark:text-white">${listing.rating}</span>
</div>
</div>
<!-- Location -->
<div class="flex items-center gap-2 text-slate-600 dark:text-slate-400 mb-3">
<i data-feather="map-pin" class="w-4 h-4 flex-shrink-0"></i>
<span class="text-sm truncate">${listing.location}</span>
</div>
<!-- University -->
<div class="flex items-center gap-2 text-slate-500 dark:text-slate-500 mb-4">
<i data-feather="book-open" class="w-4 h-4 flex-shrink-0"></i>
<span class="text-xs truncate">${listing.university}</span>
</div>
<!-- Amenities -->
<div class="flex flex-wrap gap-2 mb-4">
${listing.amenities.slice(0, 3).map(amenity => `
<span class="px-2 py-1 text-xs bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 rounded-md">
${amenity}
</span>
`).join('')}
${listing.amenities.length > 3 ? `
<span class="px-2 py-1 text-xs bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400 rounded-md">
+${listing.amenities.length - 3}
</span>
` : ''}
</div>
<!-- Footer -->
<div class="flex items-center justify-between pt-4 border-t border-slate-100 dark:border-slate-700">
<div>
<div class="flex items-baseline gap-2">
<span class="text-2xl font-bold text-primary-600 dark:text-primary-400">£${listing.price}</span>
<span class="text-sm text-slate-500 dark:text-slate-400">/week</span>
</div>
${listing.originalPrice > listing.price ? `
<span class="text-sm text-slate-400 line-through">£${listing.originalPrice}/week</span>
` : ''}
</div>
<button
class="view-details-btn px-4 py-2 bg-slate-900 dark:bg-white text-white dark:text-slate-900 font-medium rounded-lg hover:bg-primary-600 dark:hover:bg-primary-400 transition-colors flex items-center gap-2"
data-id="${listing.id}"
>
View
<i data-feather="arrow-right" class="w-4 h-4"></i>
</button>
</div>
</div>
</article>
`;
}
// Favorite Management
function toggleFavorite(e, id) {
e.stopPropagation();
if (favorites.has(id)) {
favorites.delete(id);
showToast('Removed from favorites', 'heart');
} else {
favorites.add(id);
showToast('Added to favorites', 'heart');
}
saveFavorites();
renderListings();
}
function saveFavorites() {
localStorage.setItem('amberlist_favorites', JSON.stringify([...favorites]));
}
function loadFavorites() {
const saved = localStorage.getItem('amberlist_favorites');
if (saved) {
favorites = new Set(JSON.parse(saved));
}
}
// Dark Mode
function checkDarkMode() {
const saved = localStorage.getItem('amberlist_darkmode');
isDarkMode = saved === 'true' || (!saved && window.matchMedia('(prefers-color-scheme: dark)').matches);
applyDarkMode();
}
function toggleDarkMode() {
isDarkMode = !isDarkMode;
localStorage.setItem('amberlist_darkmode', isDarkMode);
applyDarkMode();
}
function applyDarkMode() {
if (isDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}
// Utility Functions
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function showToast(message, icon = 'check') {
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'toast';
toast.innerHTML = `
<i data-feather="${icon}" class="w-5 h-5 text-primary-500"></i>
<span class="font-medium text-slate-800 dark:text-white">${message}</span>
`;
document.body.appendChild(toast);
feather.replace();
requestAnimationFrame(() => toast.classList.add('show'));
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 2500);
}
// PWA Install Prompt
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault();
deferredPrompt = e;
// Show install banner after 3 seconds
setTimeout(() => {
const installBanner = document.getElementById('installBanner');
if (installBanner && !window.matchMedia('(display-mode: standalone)').matches) {
installBanner.classList.remove('hidden');
}
}, 3000);
});
document.getElementById('installBtn')?.addEventListener('click', async () => {
if (!deferredPrompt) return;
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
if (outcome === 'accepted') {
showToast('App installed successfully!', 'download');
document.getElementById('installBanner')?.classList.add('hidden');
}
deferredPrompt = null;
});
// Hide install banner when installed
window.addEventListener('appinstalled', () => {
document.getElementById('installBanner')?.classList.add('hidden');
deferredPrompt = null;
});
function updateListingCount() {
listingCount.textContent = filteredListings.length;
}
function updateEmptyState() {
if (filteredListings.length === 0) {
emptyState.classList.remove('hidden');
listingsScrollContainer.classList.add('hidden');
loadMoreBtn.classList.add('hidden');
} else {
emptyState.classList.add('hidden');
listingsScrollContainer.classList.remove('hidden');
loadMoreBtn.classList.remove('hidden');
}
}
function clearAllFilters() {
searchInput.value = '';
priceFilter.value = '';
handleSearch();
showToast('All filters cleared', 'refresh-cw');
}
function loadMoreListings() {
loadMoreBtn.innerHTML = '<div class="w-5 h-5 border-2 border-slate-400 border-t-transparent rounded-full animate-spin"></div> Loading...';
setTimeout(() => {
// In a real app, this would fetch more from API
showToast('No more properties available', 'info');
loadMoreBtn.innerHTML = `
<i data-feather="check" class="w-5 h-5"></i>
All loaded
`;
loadMoreBtn.disabled = true;
loadMoreBtn.classList.add('opacity-50', 'cursor-not-allowed');
feather.replace();
}, 1500);
}
function showListingDetails(id) {
const listing = listingsData.find(l => l.id === id);
if (!listing) return;
// In a real app, this would open a modal or navigate to detail page
showToast(`Viewing details for ${listing.title}`, 'home');
}
// Scroll button visibility
function updateScrollButtons() {
const { scrollLeft, scrollWidth, clientWidth } = listingsScrollContainer;
const canScrollLeft = scrollLeft > 10;
const canScrollRight = scrollLeft < scrollWidth - clientWidth - 10;
scrollLeftBtn.style.opacity = canScrollLeft ? '1' : '0';
scrollLeftBtn.style.pointerEvents = canScrollLeft ? 'auto' : 'none';
scrollRightBtn.style.opacity = canScrollRight ? '1' : '0';
scrollRightBtn.style.pointerEvents = canScrollRight ? 'auto' : 'none';
}
// Expose functions globally for components
window.toggleDarkMode = toggleDarkMode;
window.Unilo = {
search: handleSearch,
getFavorites: () => [...favorites],
toggleFavorite
};
// Update nav component reference
const updateNavFavorites = () => {
const nav = document.querySelector('amber-nav');
if (nav && nav.updateFavoritesCount) {
nav.updateFavoritesCount();
}
};
// Call updateNavFavorites when favorites change
const originalToggleFavorite = toggleFavorite;
toggleFavorite = function(e, id) {
originalToggleFavorite(e, id);
updateNavFavorites();
};