Javascript Load More Content On Click Button

Javascript load more content on the click button and is easy to use in your e-commerce or blog websites to show more products or blog posts. It loads more results button is created by using javascript.

HTML

<!-- List of your items -->
<div class="list">
    <div class="list-element">Product 1</div>
    <div class="list-element">Product 2</div>
    <div class="list-element">Product 3</div>
    <div class="list-element">Product 4</div>
    <div class="list-element">Product 5</div>
    <div class="list-element">Product 6</div>
</div>

<!-- Load More Button -->
<button id="loadmore">Load More...</button>

CSS

.list {
    margin: 0px auto;
    width: 80%;
    box-sizing: border-box;
}
.list-element {
    width: 100%;
    margin: 25px 0px;
    font-family: arial;
    border-radius: 50px;
    padding: 10px 0px;
    color: #2196f3;
    font-size: 20px;
    text-align: center;
    box-shadow: 0px 0px 6px 0px #848484;
    display: none;
}
#loadmore {
    margin: 50px auto 0px;
    display: table;
    border: none;
    padding: 10px 20px;
    font-size: 18px;
    cursor: pointer;
    color: #fff;
    border-radius: 4px;
    background-color: #2196f3;
}
.list .list-element:nth-child(1) {
    display: block;
}
.list .list-element:nth-child(2) {
    display: block;
}

JavaScript

const loadmore = document.querySelector('#loadmore');
let currentItems = 2;
loadmore.addEventListener('click', (e) => {
    const elementList = [...document.querySelectorAll('.list .list-element')];
    for (let i = currentItems; i < currentItems + 2; i++) {
        if (elementList[i]) {
            elementList[i].style.display = 'block';
        }
    }
    currentItems += 2;

    // Load more button will be hidden after list fully loaded
    if (currentItems >= elementList.length) {
        event.target.style.display = 'none';
    }
})