الهدف التعليمي

تعلم كيفية عرض الكتب وتصنيفها باستخدام JavaScript، مع حساب إجمالي عدد الصفحات في المكتبة.

مكتبتنا

الشرح البرمجي
// بيانات المكتبة
const library = {
    fiction: [
        { title: "Neon Dreams", author: "Author Cyber", pages: 150 },
        { title: "Electric Shadows", author: "Author Spark", pages: 200 }
    ],
    science: [
        { title: "Quantum Realms", author: "Author Quark", pages: 300 },
        { title: "Cosmic Light", author: "Author Astro", pages: 250 }
    ]
};

// حساب الإجمالي
function calculateTotalPages() {
    return Object.values(library).flat().reduce((total, book) => total + book.pages, 0);
}

// عرض الكتب
function displayBooks() {
    const container = document.getElementById("libraryContainer");
    container.innerHTML = "";

    Object.entries(library).forEach(([category, books]) => {
        const section = document.createElement("div");
        section.className = "category-section";
        
        const header = document.createElement("div");
        header.className = "category-header";
        header.innerHTML = `<h2>كتب ${category}</h2>`;
        
        const grid = document.createElement("div");
        grid.className = "books-grid";
        
        books.forEach(book => {
            const bookDiv = document.createElement("div");
            bookDiv.className = "book";
            bookDiv.innerHTML = `
                <h3>${book.title}</h3>
                <p>المؤلف: ${book.author}</p>
                <p>الصفحات: ${book.pages}</p>
            `;
            grid.appendChild(bookDiv);
        });
        
        section.appendChild(header);
        section.appendChild(grid);
        container.appendChild(section);
    });
    
    document.getElementById("totalPages").textContent = `إجمالي الصفحات في المكتبة: ${calculateTotalPages()}`;
}

// نسخ الكود
function copyCode() {
    const code = document.querySelector('.code-container code').innerText;
    navigator.clipboard.writeText(code)
        .then(() => {
            const btn = document.querySelector('.code-header button');
            btn.innerHTML = '<i class="fas fa-check"></i> تم النسخ!';
            setTimeout(() => {
                btn.innerHTML = '<i class="far fa-copy"></i> نسخ الكود';
            }, 2000);
        })
        .catch(() => alert('فشل نسخ الكود'));
}

// التشغيل الأولي
displayBooks();