"Load more" Button in Vanilla Javascript

Beispiel für eine "Mehr laden" Funktionalität.

let parent = document.querySelector('.news')

if (!parent === false) {

    let items = parent.querySelectorAll('.news-item');
    let loadMoreBtn = document.querySelector('.load-more');
    let maxItems = 3;
    let hiddenClass = "hidden-news";

    [].forEach.call(items, function (item, idx) {
        if (idx > maxItems - 1) {
            item.classList.add(hiddenClass);
        }
    });

    loadMoreBtn.addEventListener('click', function (e) {

        e.stopPropagation();
        e.preventDefault();

        [].forEach.call(document.querySelectorAll('.' + hiddenClass), function (item, idx) {
            if (idx < maxItems - 1) {
                item.classList.remove(hiddenClass);
            }

            if (document.querySelectorAll('.' + hiddenClass).length === 0) {
                loadMoreBtn.style.opacity = '0';
            }

        });

    });
}

 

Tags