MastersAcademy / fe-course-basic-2023

Репозиторій з курсу "Front-End for beginners 2023" проекту Masters Academy - https://www.facebook.com/cherkasy.masters/
https://mastersacademy.github.io/fe-course-basic-2023/
MIT License
3 stars 26 forks source link

Homework 8 - DOM manipulation #362

Open vladyslav-yermolin-moc opened 7 months ago

vladyslav-yermolin-moc commented 7 months ago

Підготовка

Як зазвичай, початок розробки нової функціональності (нового завдання) відбувається з актуальної версії продакшена (гілка main).

  1. Перемкніться на гілку main та завантажте найновішу версію з нашого репозиторію.
  2. Заведіть нову гілку під назвою 8-dom_<ім'я користувача github>.

Завдання

Крок 1. Підготовка структури файлів:

  1. В папці скриптів вашого проєкту створіть новий файл games.js/pokemons.js та підключіть його на сторінку (далі в описі я буду описувати флоу для проєкта з іграми - для проєкта з покемонами коррегуйте назви відповідно).
  2. Скопіюйте в цей файл моки даних з файлів games-mock.js / pokemons-mock.js. Це - та структура даних, яку буде повертати бекенд у наступному завданні, тож назви змінних можуть не сподобатися нашому лінтеру. Підкорегуйте їх, якщо треба.

Крок 2. Відображення однакових карток:

На цьому кроці, мі позбавимость копі-пасти в html та відобразимо однакові картки за допомогою js.

  1. Зробіть шаблон картки. Для цього, оберніть одну з карток в тег <template data-type="card-template">.
  2. Інші картки видаліть.
  3. Напишіть функцію createCardElement, яка має
    • Знаходити темлейт картки (по data-атрибуту).
    • Робити його копію. (до речі, спробуйте не копіювати темлейт, та подивіться до чого це призведе).
    • Повертати content цієї копії.
  4. Напишіть функцію renderCards(container, cardsAmount), яка має
    • Створювати фрагмент документа.
    • cardsAmount раз створювати картку за допомогою функції createCardElement та додавати її до фрагмента.
    • у кінці фрагмент має додаватися до елемента container
  5. Додайте до ul, де раніше були картки, необхідний data-атрибут.
  6. Відобразіть 10 карток за допомогою функції renderCards у цьому ul, який потрібно знайти по доданому data-атрибуту.

Крок 3. Кастомізація карток:

На цьому кроці, ми додамо дінамічний контент до наших карток.

  1. Додайте відповідні data-атрибути до тих значень, які ви будете змінювати. Мінімум - це назва, картинка та дата релізу (зріст для покемонів). Приклад:
    <template data-type="card-template">
    <li class="card__item">
    <article class="card__content">
      <div class="card__top-row">
        <h2 class="card__title" data-card-title><h2>
        <img class="card__img" data-card-img>
    ...
  2. Доробіть функцію createCardElement:
    • Вона має приймати параметр game(або pokemon).
    • Шукати в темплейті елементи, які ми будемо змінювати (наприклад назву по data-card-title).
    • Міняти їх контент на те, що буде приходити у параметрі (наприклад встановлювати src картинки з games.thumbnail).
  3. Доробіть функцію renderCards:
    • Вона провинна приймати массив замоканних ігор games замість числа cardsAmount: renderCards(cardsContainer, games).
    • Проходитися по цьому масиву, та створювати елемент картки, викликая createCardElement(game).
    • В кінці так само фрагмент додається до контейнера.
  4. Відобразіть кастомізовані картки за допомогою функції renderCards передаючи в неї замокані ігри games

Крок 4. Фільтрація карток:

На цьому кроці, ми поєднаємо фільтри та картки.

  1. Додайте необхідні data-атрибути до чекбоксів або форми. Додайте обробники подій зміни стана чекбоксів. Корисна стаття про работу із формами - https://uk.javascript.info/form-elements
  2. При зміні стану чекбокса, необхідно фільтрувати масив замоканих даних, та перемальовувати картки.
    • Для ігор:
    • При обраном чекбоксі New мають відображатися ігри із датою реліза після 2020 року
    • При обраном чекбоксі Old - ігри із датою реліза до 2010 року
    • При обраних чекбоксах New та Old - ігри до 2010 та після 2020 року
    • Якщо чекбокси не обрані - мають відображатися всі картки
    • Для покемонів:
    • При обраном чекбоксі Big мають відображатися покемони вище 100`(футів)
    • При обраном чекбоксі Small - покемони нижче 50`
    • При обраних чекбоксах Big та Small - покемони нижче 50` та вище 100`
    • Якщо чекбокси не обрані - мають відображатися всі картки
  3. Іншим фільтрам додайте атрибут disabled, щоб ми розуміли, які елементи працюють, а які - ні.
  4. Додайте функцію init яка буде навішувати обробники подій, та відмальовувати картки без фільтації уперше, після завантаження сторінки. Це буде точка входу у ваш скріпт, те місце де все починається.

Завдання із зірочкой

  1. Додайте дінамічне наповнення для карток для всіх властивостей замоканих даних. Якщо опис буде завеликий - обріжте його, та додайте ... у кінці, як на скріні. Можна використати шаблону строку, як темплейт:
    const createGameCardStr = (game) => `
    <li class="card__item">
    <article class="card__content">
        <img src="${game.thumbnail}">
        <div>
            <h3 class="card__title">${game.titletitle}</h3>
    ...
  2. Додайте функціонал фільтрації для селекта та пошуку за текстом у назві та опису. Пошук має бути регистронезалежним, тобто по словах battle, BATTLE, BaTtLe мають показуватися картки у назві або опису яких є battle, Battle аб навіть bAttlE. Update: жовту підсвітку текста в картках робити не треба.

image

  1. Фільтрація по різним елементам має додаватися, зменьшуючи вибірку. Тобто, якщо обрані нові ігри, та по тексту шукається battle - мають бути показані тільки нові ігри із текстом battle в назві або описі.

Дедлайни

vladyslav-yermolin-moc commented 7 months ago
// games-mock.js
const games = [
    {
        id: 1136,
        title: 'Overwatch 2',
        thumbnail: 'https://www.mmobomb.com/g/1136/thumbnail.jpg',
        short_description: 'Big changes come to the Overwatch formula in this sequel...and so does PvE content, eventually.',
        game_url: 'https://www.mmobomb.com/open/overwatch-2',
        genre: 'Shooter',
        platform: 'PC (Windows)',
        publisher: 'Activision Blizzard King',
        developer: 'Blizzard Entertainment',
        release_date: '2022-10-04',
        profile_url: 'https://www.mmobomb.com/overwatch-2',
    },
    {
        id: 523,
        title: 'Lost Ark',
        thumbnail: 'https://www.mmobomb.com/g/523/thumbnail.jpg',
        short_description: 'Journey throughout the realm of Arkesia and do battle against a demon invasion in Smilegate\'s free-to-play ARPG Lost Ark!',
        game_url: 'https://www.mmobomb.com/open/lost-ark',
        genre: 'ARPG',
        platform: 'PC (Windows)',
        publisher: 'Amazon Games',
        developer: 'Smilegate',
        release_date: '2022-02-11',
        profile_url: 'https://www.mmobomb.com/lost-ark',
    },
    {
        id: 1113,
        title: 'PUBG: BATTLEGROUNDS',
        thumbnail: 'https://www.mmobomb.com/g/1113/thumbnail.jpg',
        short_description: 'Battle the odds in a 100v1 death match in PUBG: Battlegrounds, the classic free-to-play battle royale experience.',
        game_url: 'https://www.mmobomb.com/open/pubg',
        genre: 'Shooter',
        platform: 'PC (Windows)',
        publisher: 'KRAFTON, Inc.',
        developer: 'KRAFTON, Inc.',
        release_date: '2022-01-12',
        profile_url: 'https://www.mmobomb.com/pubg',
    },
    {
        id: 508,
        title: 'Enlisted',
        thumbnail: 'https://www.mmobomb.com/g/508/thumbnail.jpg',
        short_description: 'Step into the most famous battles of World War II in Enlisted, a free-to-play shooter from the makers of War Thunder. Experience squad-based combat from the ground level, as you command your troops, outfitted with era-authentic weapons and gear, in massive battles with over a hundred soldiers apiece.',
        game_url: 'https://www.mmobomb.com/open/enlisted',
        genre: 'Shooter',
        platform: 'PC (Windows)',
        publisher: 'Gaijin Entertainment',
        developer: 'Darkflow Software',
        release_date: '2021-04-08',
        profile_url: 'https://www.mmobomb.com/enlisted',
    },
    {
        id: 1120,
        title: 'Fall Guys',
        thumbnail: 'https://www.mmobomb.com/g/1120/thumbnail.jpg',
        short_description: 'Fall Guys is a free-to-play massively multiplayer party royale game.',
        game_url: 'https://www.mmobomb.com/open/fall-guys',
        genre: 'Battle Royale',
        platform: 'PC (Windows)',
        publisher: 'Mediatonic',
        developer: 'Mediatonic',
        release_date: '2020-08-04',
        profile_url: 'https://www.mmobomb.com/fall-guys',
    },
    {
        id: 340,
        title: 'Game Of Thrones Winter Is Coming',
        thumbnail: 'https://www.mmobomb.com/g/340/thumbnail.jpg',
        short_description: 'Fame and glory await you in Westeros, in Game of Thrones: Winter Is Coming, the officially licensed free-to-play browser game based on the epic fantasy series by George R.R. Martin.',
        game_url: 'https://www.mmobomb.com/open/game-of-thrones-winter-is-coming',
        genre: 'Strategy',
        platform: 'Web Browser',
        publisher: 'GTArcade',
        developer: 'YOOZOO Games ',
        release_date: '2019-11-14',
        profile_url: 'https://www.mmobomb.com/game-of-thrones-winter-is-coming',
    },
    {
        id: 427,
        title: 'Drakensang Online',
        thumbnail: 'https://www.mmobomb.com/g/427/thumbnail.jpg',
        short_description: 'Drakensang Online is a free to play 3D action RPG game that features extraordinary 3D graphics and effects and heralds the next generation of free-to-play online browser games. With the ability to customize your character, skills and magic powers like never before, join your comrades to wage a brutal war against evil.',
        game_url: 'https://www.mmobomb.com/open/drakensang-online',
        genre: 'MMORPG',
        platform: 'Web Browser',
        publisher: 'Bigpoint',
        developer: 'Bigpoint',
        release_date: '2011-08-08',
        profile_url: 'https://www.mmobomb.com/drakensang-online',
    },
    {
        id: 380,
        title: 'Dark Orbit Reloaded',
        thumbnail: 'https://www.mmobomb.com/g/380/thumbnail.jpg',
        short_description: 'Take part in huge intergalactic battles and take on the whole galaxy in DarkOrbit, the free-to-play browser-based space combat MMO from Bigpoint -- now in 3-D! Choose your faction and your ship, each with their own strengths, and take off into adventure!',
        game_url: 'https://www.mmobomb.com/open/darkorbit',
        genre: 'Shooter',
        platform: 'Web Browser',
        publisher: 'Bigpoint',
        developer: 'Bigpoint',
        release_date: '2006-12-11',
        profile_url: 'https://www.mmobomb.com/darkorbit',
    },
    {
        id: 1122,
        title: 'MultiVersus',
        thumbnail: 'https://www.mmobomb.com/g/1122/thumbnail.jpg',
        short_description: 'Match up in 1v1, 2v2 co-op, or 4-person free-for-all modes in this free-to-play Smash-Style Brawler!',
        game_url: 'https://www.mmobomb.com/open/multiversus',
        genre: 'Fighting',
        platform: 'PC (Windows)',
        publisher: 'Warner Bros. Games',
        developer: 'Player First Games',
        release_date: '2022-07-19',
        profile_url: 'https://www.mmobomb.com/multiversus',
    },
    {
        id: 5,
        title: 'Crossout',
        thumbnail: 'https://www.mmobomb.com/g/5/thumbnail.jpg',
        short_description: 'Trick out your ride and take to the post-apocalyptic roads for battle in Crossout, the free-to-play vehicular combat game from Gaijin Entertainment! Featuring a vehicle design system with endless customization and fast-paced, armor-crunching combat, Crossout offers high-octane excitement in brief and explosive matches.',
        game_url: 'https://www.mmobomb.com/open/crossout',
        genre: 'Shooter',
        platform: 'PC (Windows)',
        publisher: 'Targem',
        developer: 'Gaijin',
        release_date: '2017-05-30',
        profile_url: 'https://www.mmobomb.com/crossout',
    },
];
vladyslav-yermolin-moc commented 7 months ago
// pokemons-mock.js
const pokemons = [
    {
        abilities: [
            'Overgrow',
        ],
        detailPageURL: '/us/pokedex/bulbasaur',
        weight: 15.2,
        weakness: [
            'Fire',
            'Psychic',
            'Flying',
            'Ice',
        ],
        number: '0001',
        height: 28.0,
        collectibles_slug: 'bulbasaur',
        featured: 'true',
        slug: 'bulbasaur',
        name: 'Bulbasaur',
        ThumbnailAltText: 'Bulbasaur',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/001.png',
        id: 1,
        type: [
            'grass',
            'poison',
        ],
    },
    {
        abilities: [
            'Overgrow',
        ],
        detailPageURL: '/us/pokedex/ivysaur',
        weight: 28.7,
        weakness: [
            'Fire',
            'Psychic',
            'Flying',
            'Ice',
        ],
        number: '0002',
        height: 39.0,
        collectibles_slug: 'ivysaur',
        featured: 'true',
        slug: 'ivysaur',
        name: 'Ivysaur',
        ThumbnailAltText: 'Ivysaur',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/002.png',
        id: 2,
        type: [
            'grass',
            'poison',
        ],
    },
    {
        abilities: [
            'Overgrow',
        ],
        detailPageURL: '/us/pokedex/venusaur',
        weight: 9999.0,
        weakness: [
            'Fire',
            'Psychic',
            'Flying',
            'Ice',
        ],
        number: '0003',
        height: 945.0,
        collectibles_slug: 'venusaur',
        featured: 'true',
        slug: 'venusaur',
        name: 'Venusaur',
        ThumbnailAltText: 'Venusaur',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/003.png',
        id: 3,
        type: [
            'grass',
            'poison',
        ],
    },
    {
        abilities: [
            'Thick Fat',
        ],
        detailPageURL: '/us/pokedex/venusaur',
        weight: 342.8,
        weakness: [
            'Fire',
            'Psychic',
            'Flying',
            'Ice',
        ],
        number: '0003',
        height: 94.0,
        collectibles_slug: 'venusaur',
        featured: 'true',
        slug: 'venusaur',
        name: 'Venusaur',
        ThumbnailAltText: 'Venusaur',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/003.png',
        id: 3,
        type: [
            'grass',
            'poison',
        ],
    },
    {
        abilities: [
            'Overgrow',
        ],
        detailPageURL: '/us/pokedex/venusaur',
        weight: 220.5,
        weakness: [
            'Fire',
            'Psychic',
            'Flying',
            'Ice',
        ],
        number: '0003',
        height: 79.0,
        collectibles_slug: 'venusaur',
        featured: 'true',
        slug: 'venusaur',
        name: 'Venusaur',
        ThumbnailAltText: 'Venusaur',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/003.png',
        id: 3,
        type: [
            'grass',
            'poison',
        ],
    },
    {
        abilities: [
            'Blaze',
        ],
        detailPageURL: '/us/pokedex/charmander',
        weight: 18.7,
        weakness: [
            'Water',
            'Ground',
            'Rock',
        ],
        number: '0004',
        height: 24.0,
        collectibles_slug: 'charmander',
        featured: 'true',
        slug: 'charmander',
        name: 'Charmander',
        ThumbnailAltText: 'Charmander',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/004.png',
        id: 4,
        type: [
            'fire',
        ],
    },
    {
        abilities: [
            'Blaze',
        ],
        detailPageURL: '/us/pokedex/charmeleon',
        weight: 41.9,
        weakness: [
            'Water',
            'Ground',
            'Rock',
        ],
        number: '0005',
        height: 43.0,
        collectibles_slug: 'charmeleon',
        featured: 'true',
        slug: 'charmeleon',
        name: 'Charmeleon',
        ThumbnailAltText: 'Charmeleon',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/005.png',
        id: 5,
        type: [
            'fire',
        ],
    },
    {
        abilities: [
            'Blaze',
        ],
        detailPageURL: '/us/pokedex/charizard',
        weight: 9999.0,
        weakness: [
            'Water',
            'Electric',
            'Rock',
        ],
        number: '0006',
        height: 1102.0,
        collectibles_slug: 'charizard',
        featured: 'true',
        slug: 'charizard',
        name: 'Charizard',
        ThumbnailAltText: 'Charizard',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/006.png',
        id: 6,
        type: [
            'fire',
            'flying',
        ],
    },
    {
        abilities: [
            'Drought',
        ],
        detailPageURL: '/us/pokedex/charizard',
        weight: 221.6,
        weakness: [
            'Water',
            'Electric',
            'Rock',
        ],
        number: '0006',
        height: 67.0,
        collectibles_slug: 'charizard',
        featured: 'true',
        slug: 'charizard',
        name: 'Charizard',
        ThumbnailAltText: 'Charizard',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/006.png',
        id: 6,
        type: [
            'fire',
            'flying',
        ],
    },
    {
        abilities: [
            'Tough Claws',
        ],
        detailPageURL: '/us/pokedex/charizard',
        weight: 243.6,
        weakness: [
            'Ground',
            'Rock',
            'Dragon',
        ],
        number: '0006',
        height: 67.0,
        collectibles_slug: 'charizard',
        featured: 'true',
        slug: 'charizard',
        name: 'Charizard',
        ThumbnailAltText: 'Charizard',
        ThumbnailImage: 'https://assets.pokemon.com/assets/cms2/img/pokedex/detail/006.png',
        id: 6,
        type: [
            'fire',
            'dragon',
        ],
    },
];