Certainly! I've reviewed your HTML, CSS, and JavaScript code to identify and fix the syntax errors, particularly the "Uncaught SyntaxError: missing ) after argument list" error. The primary issue was the absence of quotation marks around URLs in your JavaScript fetch calls. Additionally, I've enhanced the UI by defining missing CSS classes and ensuring a more responsive and polished design. I've also incorporated best practices to handle edge cases, prevent memory leaks, and optimize performance.
Below is the fully corrected and optimized code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Light Novels Gallery</title>
<!-- Essential Libraries -->
<script src="https://cdn.jsdelivr.net/npm/dexie@3.2.4/dist/dexie.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fuse.js@7.0.0"></script>
<style>
/* Base styles */
body {
margin: 0;
padding: 0;
background-color: #121212;
color: #ffffff;
font-family: Arial, sans-serif;
}
.section-title {
text-align: center;
margin: 20px 0;
font-size: 24px;
color: #bb86fc;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 20px;
padding: 0 20px 40px 20px;
}
.novel-card {
background-color: #1f1b24;
border-radius: 8px;
overflow: hidden;
width: 200px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
transition: transform 0.2s;
}
.novel-card:hover {
transform: scale(1.05);
}
.novel-card img {
width: 100%;
height: 300px;
object-fit: cover;
}
.novel-content {
padding: 10px;
}
.novel-title {
font-size: 18px;
color: #bb86fc;
text-decoration: none;
display: block;
margin-bottom: 5px;
}
.post-meta {
font-size: 14px;
color: #aaaaaa;
margin-bottom: 10px;
}
.download-links {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.download-link {
background-color: #03dac6;
color: #000;
padding: 5px 10px;
border-radius: 4px;
text-decoration: none;
font-size: 12px;
transition: background-color 0.2s;
}
.download-link:hover {
background-color: #018786;
}
/* Search Container */
.search-container {
width: 100%;
max-width: 600px;
margin: 20px auto;
position: relative;
}
.search-input {
width: 100%;
padding: 12px 20px;
border: 2px solid #bb86fc;
border-radius: 25px;
background: #1f1b24;
color: #ffffff;
font-size: 16px;
transition: all 0.3s ease;
}
.search-input:focus {
outline: none;
box-shadow: 0 0 10px rgba(187, 134, 252, 0.3);
}
.search-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: #1f1b24;
border-radius: 8px;
margin-top: 5px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1000;
max-height: 300px;
overflow-y: auto;
display: none;
}
.search-result-item {
padding: 10px 15px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.search-result-item:hover {
background-color: #2d2736;
}
.search-results.visible {
display: block;
}
.placeholder-img {
background: linear-gradient(45deg, #1f1b24 25%, #2d2736 25%, #2d2736 50%, #1f1b24 50%, #1f1b24 75%, #2d2736 75%, #2d2736);
background-size: 20px 20px;
animation: moveBackground 1s linear infinite;
width: 100%;
height: 300px;
}
@keyframes moveBackground {
0% {
background-position: 0 0;
}
100% {
background-position: 20px 20px;
}
}
.scroll-top {
position: fixed;
bottom: 20px;
right: 20px;
background: #bb86fc;
color: #000;
width: 40px;
height: 40px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
opacity: 0;
transition: opacity 0.3s ease;
z-index: 1000;
font-size: 24px;
}
.scroll-top.visible {
opacity: 1;
}
/* Loading Animation */
.loading {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.8);
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 2000;
font-size: 20px;
}
.spinner {
margin-bottom: 15px;
width: 50px;
text-align: center;
}
.bounce1, .bounce2, .bounce3 {
width: 15px;
height: 15px;
background-color: #bb86fc;
border-radius: 100%;
display: inline-block;
animation: bouncedelay 1.4s infinite ease-in-out both;
}
.bounce1 {
animation-delay: -0.32s;
}
.bounce2 {
animation-delay: -0.16s;
}
@keyframes bouncedelay {
0%, 80%, 100% {
transform: scale(0);
}
40% {
transform: scale(1);
}
}
.loading-skeleton {
background: linear-gradient(90deg, #1f1b24 25%, #2d2736 50%, #1f1b24 75%);
background-size: 200% 100%;
animation: loading 1.5s infinite;
}
@keyframes loading {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.error-message {
background: #cf6679;
color: #000;
padding: 10px 20px;
border-radius: 4px;
margin: 10px 20px;
display: flex;
align-items: center;
gap: 10px;
}
.retry-button {
background: #03dac6;
border: none;
padding: 5px 15px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.retry-button:hover {
background: #018786;
}
</style>
</head>
<body>
<!-- Search Container -->
<div class="search-container">
<input type="text" class="search-input" placeholder="Search light novels..." id="searchInput">
<div class="search-results" id="searchResults"></div>
</div>
<!-- Loading Indicator -->
<div id="loading" class="loading">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
Loading...
</div>
<!-- New Updates Section -->
<h2 class="section-title">New Updates</h2>
<div id="updates" class="container"></div>
<!-- Popular Light Novels Section -->
<h2 class="section-title">Popular Light Novels</h2>
<div id="popular" class="container"></div>
<!-- Scroll to Top Button -->
<button id="scrollTop" class="scroll-top" aria-label="Scroll to top">↑</button>
<script>
// Initialize Dexie with optimized schema
const db = new Dexie('LightNovelsDB');
db.version(2).stores({
updates: '++id, title, link, imageUrl, date, downloadLinks, timestamp',
popular: '++id, title, link, imageUrl, timestamp',
metadata: 'key, value'
});
// Constants
const BATCH_SIZE = 20;
const DATA_EXPIRY = 1000 * 60 * 60; // 1 hour
const PLACEHOLDER_IMAGE = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="300" viewBox="0 0 200 300"%3E%3Crect width="100%25" height="100%25" fill="%231f1b24"/%3E%3Ctext x="50%25" y="50%25" dominant-baseline="middle" text-anchor="middle" fill="%23bb86fc"%3ENo Image%3C/text%3E%3C/svg%3E';
// State management
const state = {
updates: [],
popular: [],
currentBatch: { updates: 0, popular: 0 },
searchIndex: null
};
// Initialize Fuse.js for fuzzy search
function initializeSearch(data) {
const options = {
keys: ['title'],
threshold: 0.3,
distance: 100
};
state.searchIndex = new Fuse(data, options);
}
// Utility functions
const debounce = (fn, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
};
function isDataExpired(timestamp) {
return !timestamp || Date.now() - timestamp > DATA_EXPIRY;
}
async function fetchWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return await response.text();
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
}
// Data fetching and parsing
async function fetchAndParseData(url, isUpdates = false) {
try {
const proxyUrl = 'https://api.codetabs.com/v1/proxy?quest=' + encodeURIComponent(url);
const html = await fetchWithTimeout(proxyUrl);
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
if (isUpdates) {
return Array.from(doc.querySelectorAll('article'))
.map(element => {
try {
const titleElement = element.querySelector('.post-title a');
const imageElement = element.querySelector('.featured-media img');
const dateElement = element.querySelector('.post-date');
const downloadLinksElements = Array.from(element.querySelectorAll('.post-content p a'));
return {
title: titleElement?.textContent?.trim() || 'No Title',
link: titleElement?.href || '#',
imageUrl: imageElement?.src || PLACEHOLDER_IMAGE,
date: dateElement?.textContent?.trim() || '',
downloadLinks: downloadLinksElements
.filter(a => a.textContent.match(/VOLUME|PDF|Download/i))
.map(a => ({
href: a.href,
text: a.textContent.trim()
})),
timestamp: Date.now()
};
} catch (error) {
console.error('Error parsing update:', error);
return null;
}
})
.filter(Boolean);
} else {
return Array.from(doc.querySelectorAll('h3 a[href*="jnovels.com"]'))
.map(element => {
try {
const imageElement = element.closest('div').querySelector('img');
return {
title: element.textContent.trim() || 'No Title',
link: element.href || '#',
imageUrl: imageElement?.src || PLACEHOLDER_IMAGE,
timestamp: Date.now()
};
} catch (error) {
console.error('Error parsing popular:', error);
return null;
}
})
.filter(Boolean);
}
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
// Rendering functions
function renderNovel(novel, container) {
const div = document.createElement('div');
div.className = 'novel-card';
div.innerHTML = `
<a href="${novel.link}" target="_blank" rel="noopener noreferrer">
<img src="${novel.imageUrl}"
alt="${novel.title}"
loading="lazy"
onerror="this.src='${PLACEHOLDER_IMAGE}'">
</a>
<div class="novel-content">
<a href="${novel.link}" target="_blank" rel="noopener noreferrer" class="novel-title">
${novel.title}
</a>
${novel.date ? `<div class="post-meta">${novel.date}</div>` : ''}
${novel.downloadLinks && novel.downloadLinks.length > 0 ? `
<div class="download-links">
${novel.downloadLinks.map(link => `
<a href="${link.href}" target="_blank" rel="noopener noreferrer"
class="download-link">${link.text}</a>
`).join('')}
</div>
` : ''}
</div>
`;
container.appendChild(div);
}
function renderBatch(type, container) {
const data = state[type];
const start = state.currentBatch[type];
const end = Math.min(start + BATCH_SIZE, data.length);
for (let i = start; i < end; i++) {
renderNovel(data[i], container);
}
state.currentBatch[type] = end;
}
// Scroll handling
const handleScroll = debounce(() => {
const scrollTop = window.scrollY;
const windowHeight = window.innerHeight;
const documentHeight = document.documentElement.scrollHeight;
// Show/hide scroll to top button
document.getElementById('scrollTop').classList.toggle(
'visible',
scrollTop > windowHeight
);
// Load more content if near bottom
if (scrollTop + windowHeight > documentHeight - 500) {
const updatesContainer = document.getElementById('updates');
const popularContainer = document.getElementById('popular');
const canLoadUpdates = state.currentBatch.updates < state.updates.length;
const canLoadPopular = state.currentBatch.popular < state.popular.length;
if (canLoadUpdates) {
renderBatch('updates', updatesContainer);
}
if (canLoadPopular) {
renderBatch('popular', popularContainer);
}
}
}, 100);
// Search implementation
function setupSearch() {
const searchInput = document.getElementById('searchInput');
const searchResults = document.getElementById('searchResults');
const handleSearch = debounce((e) => {
const query = e.target.value.trim();
if (!query) {
searchResults.innerHTML = '';
searchResults.classList.remove('visible');
return;
}
const results = state.searchIndex.search(query);
if(results.length > 0){
searchResults.innerHTML = results
.slice(0, 5)
.map(({ item }) => `
<div class="search-result-item" onclick="window.location.href='${item.link}'">
${item.title}
</div>
`).join('');
searchResults.classList.add('visible');
} else {
searchResults.innerHTML = '<div class="search-result-item">No results found</div>';
searchResults.classList.add('visible');
}
}, 300);
searchInput.addEventListener('input', handleSearch);
// Hide search results when clicking outside
document.addEventListener('click', (e) => {
if (!document.querySelector('.search-container').contains(e.target)) {
searchResults.classList.remove('visible');
}
});
}
// Initialize application
async function init() {
try {
// Show loading indicator
document.getElementById('loading').style.display = 'flex';
// Check if we need to fetch new data
const metadata = await db.metadata.get('lastUpdate');
const needsUpdate = isDataExpired(metadata?.value);
if (needsUpdate) {
// Fetch new data
const [updates, popular] = await Promise.all([
fetchAndParseData('https://jnovels.com/0m-light-novels/?a=light-novels', true),
fetchAndParseData('https://jnovels.com/top-light-novels-to-read/')
]);
// Store in database
await db.transaction('rw', [db.updates, db.popular, db.metadata], async () => {
await db.updates.clear();
await db.popular.clear();
await db.updates.bulkAdd(updates);
await db.popular.bulkAdd(popular);
await db.metadata.put({ key: 'lastUpdate', value: Date.now() });
});
state.updates = updates;
state.popular = popular;
} else {
// Load from database
state.updates = await db.updates.toArray();
state.popular = await db.popular.toArray();
}
// Initialize search
initializeSearch([...state.updates, ...state.popular]);
// Render initial batches
renderBatch('updates', document.getElementById('updates'));
renderBatch('popular', document.getElementById('popular'));
// Setup event listeners
window.addEventListener('scroll', handleScroll, { passive: true });
document.getElementById('scrollTop').addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
setupSearch();
} catch (error) {
console.error('Initialization error:', error);
document.body.innerHTML += `
<div class="error-message">
Failed to load content. Please try again.
<button class="retry-button" onclick="init()">Retry</button>
</div>
`;
} finally {
// Hide loading indicator
document.getElementById('loading').style.display = 'none';
}
}
// Cleanup function to prevent memory leaks
window.addEventListener('beforeunload', () => {
window.removeEventListener('scroll', handleScroll);
});
// Start the application
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>
Key Fixes and Enhancements:
-
Syntax Errors Fixed:
-
Enhanced CSS:
- Defined Missing Classes: Added styles for
.novel-card, .container, .spinner, .download-link, and other necessary classes to ensure a cohesive and visually appealing UI.
- Responsive Design: Ensured that the layout is responsive and looks good on various screen sizes.
- Visibility Controls: Managed the visibility of elements like search results and the scroll-to-top button.
-
Improved JavaScript Logic:
-
Error Handling:
- Retry Mechanism: Added a retry button in the error message to allow users to attempt reloading the content if an error occurs.
- Logging: Enhanced error logging to the console for easier debugging.
-
Performance Optimizations:
- Debouncing: Implemented debouncing for scroll and search input events to reduce unnecessary function calls.
- Lazy Loading Images: Utilized the
loading="lazy" attribute for images to defer loading until they are about to enter the viewport, improving page load times.
- Removed event listeners appropriately to prevent memory leaks.
Final Notes:
-
CORS Proxy: The application uses https://api.codetabs.com/v1/proxy?quest= as a CORS proxy to fetch data from external sources. Ensure that this proxy is reliable and consider implementing your own proxy if necessary for better control and reliability.
-
Data Source Reliability: The selectors used in fetchAndParseData are based on the current structure of the source website (jnovels.com). If the website's structure changes, you may need to update these selectors accordingly.
-
Security Considerations: Always sanitize and validate the data fetched from external sources to prevent potential security vulnerabilities like Cross-Site Scripting (XSS).
Feel free to further customize the styles and functionalities to better fit your specific requirements. If you encounter any more issues or need additional features, don't hesitate to ask!