Фильтры в виде табов для каталога товаров

Модификация позволяет добавить к каталогу фильтры в виде табов, со счетчиком и избранным
Инструкция по настройке
Шаблон страницы
Как добавить шаблон
64162915
Для корректной работы модификаций подключите библиотеку jQuery:
Настройки сайта -> Еще -> Подключить jQuery на страницах сайта
jQuery
1 шаг
  1. В Контенте блока подключаем необходимый раздел товаров
  2. Переходим в Настройки блока - ФИЛЬТРЫ & РАЗДЕЛЫ
  3. Ставим галочки:
  • Спрятать фильтры
  • Спрятать список разделов каталога
4. Переходим во вкладку "Карточки"
5. В пункте КОЛ-ВО КАРТОЧЕК В РЯДУ выбираем 3
6. В пункте КОЛИЧЕСТВО ВИДИМЫХ БЛОКОВ ДО КНОПКИ «ЗАГРУЗИТЬ ЕЩЕ» задаем значение 100
Добавляем блок ST305N (каталог)
2 шаг
Добавляем блок T123 и копируем в него код
Скопировать код
3 шаг
Ориентируясь по комментариям в коде, вы можете изменить:
  1. Цвет фона
  2. Цвет шрифта
  3. Шрифт текста
  4. Размер текста
  5. Чтобы вывести избранное как один из пунктов, скопируйте код под строчку // МЕСТО ДЛЯ КОДА С ИЗБРАННЫМ
Настраиваем параметры в коде
Скопировать код
<!--SH11 - Модификация для Тильды. Фильтры в виде табов для каталога товаров https://mod.tistols.com/filters -->
<div id="search">
    <div id="search-input-btns">
    </div>
</div>
<style>
.js-store-grid-cont {
    display: flex; /* Делаем элементы в строку */
    flex-wrap: wrap; /* Разрешаем перенос элементов */
}
/*Добавляем фильтры для каталога модификаций + ниже делаем ссылки на фильтры*/
button.filter-button {
    color: #000000; /* Цвет текста */
    font-size: 14px; /* размер шрифта */
    font-family: 'HelveticaNeue', Arial, sans-serif;
    line-height: normal;
    font-weight: 400;
    letter-spacing: -0.5px;
    border-width: 1px;
    border-radius: 10px;
    background-position: center center;
    background-color: #F3F3F3; /* Цвет фона */
    border-color: #F3F3F3;
    border-style: solid;
    transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out, border-color 0.2s ease-in-out;
    padding: 7px 15px;
    margin: 0 10px 10px 0;
    cursor:pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}
/* Стилизация счетчика внутри кнопки */
button.filter-button .val {
    font-size: 12px;
    line-height: normal;
    text-align: center;
    color: #fff; /* Цвет текста */
    width: 25px;
    height: 25px;
    margin-left: 10px;
    margin-right: -8px;
    background: #000; /* Цвет фона */
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}
/* Стилизация счетчика при наведении */
button.filter-button:hover .val {
    color: #000;
    background: #E9FF71; /* Светло-зеленый фон */
}
/*Настраиваем состояния для кнопки Избранное в фильтрах*/
.filter-button.active .heartpic {
    filter:invert(1);
}
.filter-button:hover .heartpic {
    filter:invert(1);
}
#search {max-width:98%;margin:0 auto;}
#search-input-btns {display: flex;    flex-wrap: wrap;}
 #search-input-block {
     display: flex;
    align-items: center;
    background-color: #eee;
    border-radius: 50px;
 }
    #search-input-block input {
    background: transparent;
    outline: none;
    border: none;
    color: #000;
    font-family: 'Helvetica';
    font-size: 10px;
    font-weight: 400;
    width: 100%;
    padding: 14px 10px;
    }
    #searchButton {
            transition: 0.3s;
    cursor: pointer;
    height: 100%;
    color: #000;
    border: none;
    font-family: 'Helvetica';
    background: #e5e5e5;
    font-size: 11px;
    padding: 14px 20px;
    border-radius: 0 50px 50px 0;
    }
   
/* Стили активных и наведенных кнопок фильтра */
button.filter-button:hover,
button.filter-button.active {
    background-color: #000;
    color: #fff;
}
button.filter-button.active .val {
    color:#000;
    background: #E9FF71;
}
</style>



<script>
    // Делаем ссылки на фильтры
$(function () {
    var timer = setInterval(function () {
        if (window.tStoreXHR && Object.keys(window.tStoreXHR).length > 0) {
            var jsonData = JSON.parse(window.tStoreXHR[Object.keys(window.tStoreXHR)[0]].response);

            if (jsonData && jsonData.filters && jsonData.filters.filters && Array.isArray(jsonData.filters.filters)) {
                clearInterval(timer);

                const searchInputBtns = document.getElementById('search-input-btns');
                const urlParams = new URLSearchParams(window.location.search);
                const selectedFilter = urlParams.get('filter');

                function translit(str) {
                    const ruToEn = {
                        'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', 'ж': 'zh',
                        'з': 'z', 'и': 'i', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o', 'п': 'p',
                        'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'kh', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh',
                        'щ': 'sch', 'ъ': '', 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu', 'я': 'ya',
                        ' ': '-', ',': '', '.': '', '/': '-', '(': '', ')': ''
                    };
                    return str.toLowerCase().split('').map(char => ruToEn[char] || char).join('');
                }

                function filterProducts(filterId) {
                    document.querySelectorAll('.js-product').forEach(product => {
                        const productPartUids = product.getAttribute('data-product-part-uid');
                        if (productPartUids) {
                            const productPartsArray = productPartUids.split(',');
                            product.style.display = productPartsArray.includes(filterId) ? 'block' : 'none';
                        } else {
                            product.style.display = 'none';
                        }
                    });
                }

                jsonData.filters.filters.forEach(filter => {
                    if (filter.values && Array.isArray(filter.values)) {
                        filter.values.forEach(valueObj => {
                            const button = document.createElement('button');

                            const textSpan = document.createElement('span');
                            textSpan.textContent = valueObj.value;

                            const countSpan = document.createElement('span');
                            countSpan.classList.add('val');
                            countSpan.textContent = ` ${valueObj.count}`;

                            button.appendChild(textSpan);
                            button.appendChild(countSpan);

                            button.setAttribute('data-filter', valueObj.id);
                            button.setAttribute('data-name', valueObj.value);
                            button.classList.add('filter-button');

                            const filterSlug = translit(valueObj.value);
                            if (selectedFilter === filterSlug) {
                                button.classList.add('active');
                                filterProducts(valueObj.id);
                            }

                            button.addEventListener('click', function () {
                                document.querySelectorAll('.filter-button').forEach(btn => btn.classList.remove('active'));
                                this.classList.add('active');

                                const filterName = this.getAttribute('data-name');
                                const filterSlug = translit(filterName);

                                urlParams.set('filter', filterSlug);
                                window.history.pushState({}, '', '?' + urlParams.toString());

                                filterProducts(valueObj.id);
                            });

                            searchInputBtns.appendChild(button);
                        });
                    }
                });


   // МЕСТО ДЛЯ КОДА С ИЗБРАННЫМ

// Обновление кнопки при клике на .t1002__addBtn
$('.t1002__addBtn').on('click', function () {
  console.log('123')
    updateWishlistButton();
});



                // Делаем кнопку "All" функциональной
                const allButton = document.querySelector('[data-filter="718547608741"]');
                if (allButton) {
                    if (!selectedFilter) {
                        allButton.classList.add('active'); // Выделяем кнопку "All", если нет фильтра в URL
                    }

                    allButton.addEventListener('click', function () {
                        document.querySelectorAll('.filter-button').forEach(btn => btn.classList.remove('active'));
                        this.classList.add('active');

                        urlParams.delete('filter');
                        window.history.pushState({}, '', window.location.pathname);

                        document.querySelectorAll('.js-product').forEach(product => product.style.display = 'block');
                    });

                    if (!selectedFilter) {
                        document.querySelectorAll('.js-product').forEach(product => product.style.display = 'block'); // Показываем все продукты при первом запуске
                    }
                }

                // Удаляем `?filter=...` из URL при загрузке страницы
                if (selectedFilter) {
                    window.history.replaceState({}, '', window.location.pathname);
                }
            }
        }
    }, 1000);
});

</script>
// КОД ДОБАВЛЯЮЩИЙ ПУНКТ С ИЗБРАННЫМ

function updateWishlistButton() {
    setTimeout(function() {
        // Загружаем избранное из localStorage
        let wishlist = JSON.parse(localStorage.getItem('twishlist')) || {};
        let total = wishlist.total || 0;

        console.log("Общее количество товаров в избранном:", total);

        let wishlistButton = $('.filter-button[data-filter="wishlist"]');

        if (total > 0) {
            // Если кнопка не существует, создаем её
            if (wishlistButton.length === 0) {
                wishlistButton = $('<button>')
                    .attr('data-filter', 'wishlist')
                    .attr('data-name', 'wishlist')
                    .addClass('filter-button')
                    .append('<span><img class="heartpic" src=https://static.tildacdn.com/tild3466-3233-4864-b432-323830633964/svgexport-12_1.svg></span>')
                    // .append('<span class="val"> ' + total + '</span>')
                    .prependTo('#search-input-btns');

                // Обработчик клика добавляем один раз
                wishlistButton.on('click', function () {
                    $('.filter-button').removeClass('active');
                    $(this).addClass('active');

                    $('.js-product').hide();
                    $('.t1002__addBtn_active').closest('.js-product').show();
                });
            } else {
                // Если кнопка уже существует, обновляем её текст
                wishlistButton.find('.val').text(` ${total}`);
            }
        } else {
            // Если товаров нет, удаляем кнопку
            wishlistButton.remove();
            document.querySelectorAll('.js-product').forEach(product => product.style.display = 'block');
        }
    }, 300);  // Увеличено время ожидания
}

// Первоначальный вызов
updateWishlistButton();
Вам также может быть интересно: