Using vanilla HTML, Javascript and preferably just pure CSS I’m trying to implement a feature whereby when a user clicks a button, the next 4 elements are displayed to the user.
Due to limitations in the snippet, the styles aren’t quite reflective – as I’ve implemented a grid system, so there’s actually 4 items in a row (they’re just horizontal in the above).
By default I want to show just 4 items, but when the user selects "load more", then the next 4 are displayed & so on. The button should always remain just below the last visible element.
Can anyone guide or reference an approach that would achieve this result?
.container {
padding: 16px;
}
.items-container {
flex-direction: row;
display: flex;
gap: 16px;
}
.item {
flex: 0 0 auto;
width: 25%;
background-color: lightblue;
height: 320px;
}
<div class="container">
<div class="items-container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<p>Showing 4 of 10</p>
<button>
Load more
</button>
</div>
4
Answers
You may apply the following
When user click that button using javascript you may remove the and display the items.
Is this what you are looking for? If you are only showing the 1st 4 elements at the start then the rest needs to be hidden until you press the button.
Once you press it, loop thru all hidden elements and remove the class which hiddes those elements
d-none
in this example and change your text fromShowing 4 of 8
toShowing 8 of 8
withtextContent
Is this what you are trying to do? Explanation:
updateCount
writes the current count to thep
element.updateItems
changes the display property of your items based on the current value ofcount
. The event listener on the button increases the value of the current count by 4 and then calls theupdateItems
function, which updates the styles based on the current count and then calls theupdateCount
function to write the current page to thep
. I hope this helps!I suppose you already have the elements loaded, if not, the solution I’m going to give you won’t work completely: