Fix this enhanced code: [ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">…
- User
Fix this enhanced code: [
code - Assistant
Fix this enhanced code: [
<style>
/* CSS Variables */
:root {
--color-primary: #333;
--color-secondary: #f5f5f5;
--color-accent: #4a90e2;
--color-text: #333;
--color-background: #f5f5f5;
--color-shadow: rgba(0, 0, 0, 0.1);
--color-hover: #666;
--font-primary: 'Inter', system-ui, -apple-system, sans-serif;
--spacing-unit: 8px;
--transition-speed: 0.3s;
--border-radius: 12px;
--max-width: 1400px;
}
.dark-theme {
--color-primary: #f5f5f5;
--color-secondary: #333;
--color-text: #f5f5f5;
--color-background: #1a1a1a;
--color-shadow: rgba(255, 255, 255, 0.1);
--color-hover: #ddd;
}
/* Base Styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: var(--font-primary);
background-color: var(--color-background);
color: var(--color-text);
line-height: 1.6;
transition: background-color var(--transition-speed),
color var(--transition-speed);
}
/* Layout Components */
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 60px;
background-color: var(--color-primary);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 var(--spacing-unit);
z-index: 100;
box-shadow: 0 2px 10px var(--color-shadow);
}
.search-container {
flex: 1;
max-width: 500px;
margin: 0 var(--spacing-unit);
}
.search-input {
width: 100%;
padding: calc(var(--spacing-unit) * 1.5);
border: none;
border-radius: var(--border-radius);
background-color: var(--color-secondary);
color: var(--color-text);
font-size: 1rem;
transition: box-shadow var(--transition-speed);
}
.search-input:focus {
outline: none;
box-shadow: 0 0 0 2px var(--color-accent);
}
.grid-container {
margin-top: 80px;
padding: var(--spacing-unit);
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: calc(var(--spacing-unit) * 2);
max-width: var(--max-width);
margin-left: auto;
margin-right: auto;
}
.novel-card {
position: relative;
background-color: var(--color-secondary);
border-radius: var(--border-radius);
overflow: hidden;
transition: transform var(--transition-speed),
box-shadow var(--transition-speed);
cursor: pointer;
}
.novel-card:hover {
transform: translateY(-4px);
box-shadow: 0 4px 20px var(--color-shadow);
}
.novel-image {
width: 100%;
aspect-ratio: 2/3;
object-fit: cover;
background-color: var(--color-secondary);
}
.novel-info {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: var(--spacing-unit);
background: linear-gradient(transparent, rgba(0,0,0,0.8));
color: white;
}
.novel-title {
font-size: 1rem;
font-weight: 600;
margin-bottom: calc(var(--spacing-unit) / 2);
}
/* Utility Classes */
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
/* Loading States */
.loading-spinner {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40px;
height: 40px;
border: 3px solid var(--color-secondary);
border-top-color: var(--color-accent);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: translate(-50%, -50%) rotate(360deg); }
}
/* Responsive Design */
@media (max-width: 768px) {
.grid-container {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
}
@media (max-width: 480px) {
.search-container {
max-width: 200px;
}
}
/* Reduced Motion */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
</style>
<main class="grid-container" id="novelGrid"></main>
<div id="loadingSpinner" class="loading-spinner" role="status" aria-hidden="true"></div>
<script>
// Enhanced Configuration
const CONFIG = {
API_ENDPOINT: 'https://sh.dafeyan784.workers.dev/?target=https://jnovels.com/top-light-novels-to-read/',
BATCH_SIZE: 20,
CACHE_DURATION: 24 * 60 * 60 * 1000, // 24 hours
RETRY_ATTEMPTS: 3,
RETRY_DELAY: 1000,
IMAGE_TIMEOUT: 10000,
};
// State Management
const state = {
novels: [],
loading: false,
error: null,
currentPage: 1,
darkMode: false,
};
// Utility Functions
const debounce = (fn, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
};
const setLoading = (isLoading) => {
state.loading = isLoading;
document.getElementById('loadingSpinner').setAttribute('aria-hidden', !isLoading);
};
// DOM Manipulation
const createNovelCard = (novel) => {
const card = document.createElement('article');
card.className = 'novel-card';
const img = new Image();
img.className = 'novel-image';
img.src = novel.imageUrl;
img.alt = novel.title;
img.loading = 'lazy';
const info = document.createElement('div');
info.className = 'novel-info';
const title = document.createElement('h2');
title.className = 'novel-title';
title.textContent = novel.title;
info.appendChild(title);
card.appendChild(img);
card.appendChild(info);
card.addEventListener('click', () => {
window.open(novel.url, '_blank', 'noopener,noreferrer');
});
return card;
};
// Data Fetching
const fetchNovels = async () => {
try {
setLoading(true);
// Check cache first
const cached = localStorage.getItem('novelsCache');
if (cached) {
const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp < CONFIG.CACHE_DURATION) {
return data;
}
}
const response = await fetch(CONFIG.API_ENDPOINT);
if (!response.ok) throw new Error('Failed to fetch novels');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const novels = Array.from(doc.querySelectorAll('img[loading="lazy"][decoding="async"].alignnone'))
.map(img => ({
imageUrl: img.src,
title: img.alt || 'Unknown Title',
url: img.closest('a')?.href || '#'
}));
// Cache the results
localStorage.setItem('novelsCache', JSON.stringify({
data: novels,
timestamp: Date.now()
}));
return novels;
} catch (error) {
console.error('Error fetching novels:', error);
throw error;
} finally {
setLoading(false);
}
};
// Event Handlers
const handleSearch = debounce((event) => {
const query = event.target.value.toLowerCase();
const filteredNovels = state.novels.filter(novel =>
novel.title.toLowerCase().includes(query)
);
renderNovels(filteredNovels);
}, 300);
const toggleTheme = () => {
state.darkMode = !state.darkMode;
document.body.classList.toggle('dark-theme', state.darkMode);
localStorage.setItem('darkMode', state.darkMode);
};
// Rendering
const renderNovels = (novels) => {
const grid = document.getElementById('novelGrid');
grid.innerHTML = '';
const fragment = document.createDocumentFragment();
novels.forEach(novel => {
fragment.appendChild(createNovelCard(novel));
});
grid.appendChild(fragment);
};
// Initialization
const init = async () => {
try {
// Load theme preference
state.darkMode = localStorage.getItem('darkMode') === 'true';
document.body.classList.toggle('dark-theme', state.darkMode);
// Set up event listeners
document.querySelector('.search-input').addEventListener('input', handleSearch);
document.querySelector('.theme-button').addEventListener('click', toggleTheme);
// Load initial data
state.novels = await fetchNovels();
renderNovels(state.novels);
// Set up infinite scroll
const observer = new IntersectionObserver((entries) => {
const lastEntry = entries[entries.length - 1];
if (lastEntry.isIntersecting && !state.loading) {
// Load more novels
state.currentPage++;
// Implement pagination logic here if needed
}
});
const lastCard = document.querySelector('.novel-card:last-child');
if (lastCard) observer.observe(lastCard);
} catch (error) {
console.error('Initialization error:', error);
// Implement error handling UI
}
};
// Start the application
document.addEventListener('DOMContentLoaded', init);
</script>
Certainly! After reviewing your enhanced code, I identified a few issues that need to be addressed to ensure it functions correctly:
errorMessage Element: The JavaScript references an errorMessage element, but it isn't present in the HTML.error-message: The CSS for the .error-message class is missing.Below is the fully corrected and enhanced code addressing these issues:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Top Light Novels - Enhanced Edition</title>
<meta name="description" content="Discover and explore the top light novels with advanced features and smooth performance">
<meta name="keywords" content="light novels, top novels, reading, books, literature, recommendations">
<meta name="theme-color" content="#333333">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<style>
/* CSS Variables */
:root {
--color-primary: #333;
--color-secondary: #f5f5f5;
--color-accent: #4a90e2;
--color-text: #333;
--color-background: #f5f5f5;
--color-shadow: rgba(0, 0, 0, 0.1);
--color-hover: #666;
--font-primary: 'Inter', system-ui, -apple-system, sans-serif;
--spacing-unit: 8px;
--transition-speed: 0.3s;
--border-radius: 12px;
--max-width: 1400px;
--error-bg: #ff4d4d;
--error-text: #fff;
}
.dark-theme {
--color-primary: #f5f5f5;
--color-secondary: #333;
--color-text: #f5f5f5;
--color-background: #1a1a1a;
--color-shadow: rgba(255, 255, 255, 0.1);
--color-hover: #ddd;
--error-bg: #ff4d4d;
--error-text: #fff;
}
/* Base Styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: var(--font-primary);
background-color: var(--color-background);
color: var(--color-text);
line-height: 1.6;
transition: background-color var(--transition-speed),
color var(--transition-speed);
}
/* Layout Components */
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 60px;
background-color: var(--color-primary);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 var(--spacing-unit);
z-index: 100;
box-shadow: 0 2px 10px var(--color-shadow);
}
.menu-button,
.theme-button {
background: none;
border: none;
cursor: pointer;
padding: var(--spacing-unit);
border-radius: 50%;
transition: background-color var(--transition-speed);
}
.menu-button:hover,
.theme-button:hover {
background-color: rgba(0, 0, 0, 0.1);
}
.search-container {
flex: 1;
max-width: 500px;
margin: 0 var(--spacing-unit);
}
.search-input {
width: 100%;
padding: calc(var(--spacing-unit) * 1.5);
border: none;
border-radius: var(--border-radius);
background-color: var(--color-secondary);
color: var(--color-text);
font-size: 1rem;
transition: box-shadow var(--transition-speed);
}
.search-input:focus {
outline: none;
box-shadow: 0 0 0 2px var(--color-accent);
}
.grid-container {
margin-top: 80px;
padding: var(--spacing-unit);
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: calc(var(--spacing-unit) * 2);
max-width: var(--max-width);
margin-left: auto;
margin-right: auto;
}
.novel-card {
position: relative;
background-color: var(--color-secondary);
border-radius: var(--border-radius);
overflow: hidden;
transition: transform var(--transition-speed),
box-shadow var(--transition-speed);
cursor: pointer;
}
.novel-card:hover {
transform: translateY(-4px);
box-shadow: 0 4px 20px var(--color-shadow);
}
.novel-image {
width: 100%;
aspect-ratio: 2/3;
object-fit: cover;
background-color: var(--color-secondary);
}
.novel-info {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: var(--spacing-unit);
background: linear-gradient(transparent, rgba(0,0,0,0.8));
color: white;
}
.novel-title {
font-size: 1rem;
font-weight: 600;
margin-bottom: calc(var(--spacing-unit) / 2);
}
/* Utility Classes */
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
/* Loading States */
.loading-spinner {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40px;
height: 40px;
border: 3px solid var(--color-secondary);
border-top-color: var(--color-accent);
border-radius: 50%;
animation: spin 1s linear infinite;
z-index: 200;
display: none;
}
.loading-spinner.active {
display: block;
}
@keyframes spin {
to { transform: translate(-50%, -50%) rotate(360deg); }
}
/* Error Message */
.error-message {
position: fixed;
bottom: var(--spacing-unit);
left: 50%;
transform: translateX(-50%);
background-color: var(--error-bg);
color: var(--error-text);
padding: var(--spacing-unit);
border-radius: var(--border-radius);
box-shadow: 0 2px 10px var(--color-shadow);
z-index: 201;
display: none;
}
.error-message.active {
display: block;
}
/* Responsive Design */
@media (max-width: 768px) {
.grid-container {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
}
@media (max-width: 480px) {
.search-container {
max-width: 200px;
}
}
/* Reduced Motion */
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}
</style>
</head>
<body>
<header class="header">
<button class="menu-button" aria-label="Toggle menu">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="3" y1="12" x2="21" y2="12"></line>
<line x1="3" y1="6" x2="21" y2="6"></line>
<line x1="3" y1="18" x2="21" y2="18"></line>
</svg>
</button>
<div class="search-container">
<input type="search" class="search-input" placeholder="Search novels..." aria-label="Search novels">
</div>
<button class="theme-button" aria-label="Toggle theme">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="5"></circle>
<line x1="12" y1="1" x2="12" y2="3"></line>
<line x1="12" y1="21" x2="12" y2="23"></line>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
<line x1="1" y1="12" x2="3" y2="12"></line>
<line x1="21" y1="12" x2="23" y2="12"></line>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
</svg>
</button>
</header>
<main class="grid-container" id="novelGrid" role="main"></main>
<div id="loadingSpinner" class="loading-spinner" role="status" aria-hidden="true"></div>
<div id="errorMessage" class="error-message" role="alert" aria-live="assertive"></div>
<script>
// Enhanced Configuration
const CONFIG = {
API_ENDPOINT: 'https://sh.dafeyan784.workers.dev/?target=https://jnovels.com/top-light-novels-to-read/',
BATCH_SIZE: 20,
CACHE_DURATION: 24 * 60 * 60 * 1000, // 24 hours
RETRY_ATTEMPTS: 3,
RETRY_DELAY: 1000,
IMAGE_TIMEOUT: 10000,
};
// State Management
const state = {
novels: [],
loading: false,
error: null,
currentPage: 1,
darkMode: false,
};
// Utility Functions
const debounce = (fn, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
};
const setLoading = (isLoading) => {
state.loading = isLoading;
const spinner = document.getElementById('loadingSpinner');
if (spinner) {
if (isLoading) {
spinner.classList.add('active');
spinner.setAttribute('aria-hidden', 'false');
} else {
spinner.classList.remove('active');
spinner.setAttribute('aria-hidden', 'true');
}
}
};
const showErrorMessage = (message) => {
const errorDiv = document.getElementById('errorMessage');
if (errorDiv) {
errorDiv.textContent = message;
errorDiv.classList.add('active');
setTimeout(() => {
errorDiv.classList.remove('active');
}, 5000);
} else {
console.error('Error Message Element Not Found:', message);
}
};
// DOM Manipulation
const createNovelCard = (novel) => {
const card = document.createElement('article');
card.className = 'novel-card';
card.setAttribute('tabindex', '0'); // Make it focusable for accessibility
const img = new Image();
img.className = 'novel-image';
img.src = novel.imageUrl;
img.alt = novel.title;
img.loading = 'lazy';
img.onerror = () => {
img.src = 'https://via.placeholder.com/200x300?text=Image+Not+Available';
};
const info = document.createElement('div');
info.className = 'novel-info';
const title = document.createElement('h2');
title.className = 'novel-title';
title.textContent = novel.title;
info.appendChild(title);
card.appendChild(img);
card.appendChild(info);
card.addEventListener('click', () => {
window.open(novel.url, '_blank', 'noopener,noreferrer');
});
card.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
window.open(novel.url, '_blank', 'noopener,noreferrer');
}
});
return card;
};
// Data Fetching
const fetchNovels = async () => {
try {
setLoading(true);
// Check cache first
const cached = localStorage.getItem('novelsCache');
if (cached) {
const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp < CONFIG.CACHE_DURATION) {
return data;
}
}
const response = await fetch(CONFIG.API_ENDPOINT, { timeout: CONFIG.IMAGE_TIMEOUT });
if (!response.ok) throw new Error('Failed to fetch novels');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const novels = Array.from(doc.querySelectorAll('img[loading="lazy"].alignnone'))
.map(img => ({
imageUrl: img.src,
title: img.alt || 'Unknown Title',
url: img.closest('a')?.href || '#'
}))
.filter(novel => novel.imageUrl && novel.url !== '#');
// Cache the results
localStorage.setItem('novelsCache', JSON.stringify({
data: novels,
timestamp: Date.now()
}));
return novels;
} catch (error) {
console.error('Error fetching novels:', error);
showErrorMessage('Failed to fetch novels. Please try again later.');
return [];
} finally {
setLoading(false);
}
};
// Event Handlers
const handleSearch = debounce((event) => {
const query = event.target.value.toLowerCase();
const filteredNovels = state.novels.filter(novel =>
novel.title.toLowerCase().includes(query)
);
renderNovels(filteredNovels);
}, 300);
const toggleTheme = () => {
state.darkMode = !state.darkMode;
document.body.classList.toggle('dark-theme', state.darkMode);
localStorage.setItem('darkMode', state.darkMode);
};
// Rendering
const renderNovels = (novels) => {
const grid = document.getElementById('novelGrid');
if (!grid) return;
const fragment = document.createDocumentFragment();
novels.forEach(novel => {
fragment.appendChild(createNovelCard(novel));
});
grid.innerHTML = '';
grid.appendChild(fragment);
setupInfiniteScroll();
};
// Infinite Scroll
const setupInfiniteScroll = () => {
const grid = document.getElementById('novelGrid');
const cards = grid.querySelectorAll('.novel-card');
const lastCard = cards[cards.length - 1];
if (!lastCard) return;
const observer = new IntersectionObserver((entries) => {
const entry = entries[0];
if (entry.isIntersecting && !state.loading) {
loadMoreNovels();
observer.unobserve(entry.target);
}
}, {
rootMargin: '200px',
threshold: 0.1
});
observer.observe(lastCard);
};
const loadMoreNovels = () => {
const start = state.currentPage * CONFIG.BATCH_SIZE;
const end = start + CONFIG.BATCH_SIZE;
const batch = state.novels.slice(start, end);
if (batch.length === 0) return;
const grid = document.getElementById('novelGrid');
const fragment = document.createDocumentFragment();
batch.forEach(novel => {
fragment.appendChild(createNovelCard(novel));
});
grid.appendChild(fragment);
state.currentPage++;
// Re-setup infinite scroll for the new last card
setupInfiniteScroll();
};
// Initialization
const init = async () => {
try {
// Load theme preference
state.darkMode = localStorage.getItem('darkMode') === 'true';
document.body.classList.toggle('dark-theme', state.darkMode);
// Set up event listeners
const searchInput = document.querySelector('.search-input');
const themeButton = document.querySelector('.theme-button');
if (searchInput) {
searchInput.addEventListener('input', handleSearch);
}
if (themeButton) {
themeButton.addEventListener('click', toggleTheme);
}
// Load initial data
state.novels = await fetchNovels();
if (state.novels.length === 0) {
showErrorMessage('No novels available to display.');
return;
}
renderNovels(state.novels.slice(0, CONFIG.BATCH_SIZE));
state.currentPage = 1;
} catch (error) {
console.error('Initialization error:', error);
showErrorMessage('An unexpected error occurred. Please try again later.');
}
};
// Start the application
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>
Added errorMessage Element:
<div id="errorMessage" class="error-message" role="alert" aria-live="assertive"></div>
This element is used to display error messages to the user when something goes wrong.
CSS for .error-message:
.error-message {
position: fixed;
bottom: var(--spacing-unit);
left: 50%;
transform: translateX(-50%);
background-color: var(--error-bg);
color: var(--error-text);
padding: var(--spacing-unit);
border-radius: var(--border-radius);
box-shadow: 0 2px 10px var(--color-shadow);
z-index: 201;
display: none;
}
.error-message.active {
display: block;
}
This styles the error message to appear fixed at the bottom center of the screen with appropriate visibility toggling.
Completed Infinite Scroll Implementation:
setupInfiniteScroll Function: Observes the last novel card to trigger loading more novels when it comes into view.loadMoreNovels Function: Loads the next batch of novels based on the current page and batch size.Enhanced Accessibility:
tabindex="0" to .novel-card to make them focusable via keyboard.aria-labels and role attributes where appropriate to improve screen reader support.Robust Error Handling:
fetchNovels function now catches and displays errors effectively.Responsive Enhancements:
Lazy Loading Intersection Observer Polyfill: For better browser support, consider adding a polyfill for IntersectionObserver if you aim to support older browsers.
Accessibility Testing: Use tools like Lighthouse or Axe to further audit and enhance accessibility features.
SEO Improvements: Ensure that each novel card has relevant metadata and consider server-side rendering for better SEO performance.
By implementing these fixes and enhancements, your enhanced code should function smoothly, providing users with a seamless and accessible experience when browsing top light novels.
Not yet included in a published release.
Performance Optimizations:
DocumentFragment to batch append novel cards to the DOM, reducing reflows and repaints.Theme Persistence:
localStorage and persists across sessions.