Issue
Is it possible to add class to specific number (5) of elements? I want to make a news page where when one clicks, 5 more articles show up. Action must be repeated.
const loadMorePostsBtn = document.getElementById('loadMoreBtn');
const allPostsCheck = document.querySelectorAll('.top-news');
function moreview(){
allPostsCheck.forEach(singlepost => {
singlepost.classList.remove('hidden');
hiddenPostsPopup.textContent = $('#allNews > .hidden').length;
}
});
}
If it helps, this is code which is working but doesn't have a specific number
Solution
You should have used for
loop instead of foreach
,
because foreach
runs for all elements but in for
you can specify for example run 5 times not more
Here's a simple example:
function more() {
const amount = 5;
const hiddenPosts = document.querySelectorAll(".top-news.hidden");
const remaining = hiddenPosts.length;
if (remaining > 0) {
for (let i = 0; i < (remaining >= amount ? amount : remaining); i++) {
hiddenPosts[i].classList.remove("hidden");
}
} else {
alert('no more posts')
}
}
body {
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
}
.top-news {
padding: 15px 25%;
background: rgba(0, 0, 0, 0.5);
margin: 5px 0;
}
.top-news.hidden {
display: none;
}
<div class="top-news">1</div>
<div class="top-news">2</div>
<div class="top-news">3</div>
<div class="top-news">4</div>
<div class="top-news">5</div>
<div class="top-news hidden">6</div>
<div class="top-news hidden">7</div>
<div class="top-news hidden">8</div>
<div class="top-news hidden">9</div>
<div class="top-news hidden">10</div>
<div class="top-news hidden">11</div>
<button onclick="more()">Load More</button>
Another example with a simple fade animation:
function more() {
const amount = 5;
const hiddenPosts = document.querySelectorAll(".top-news.hidden");
const remaining = hiddenPosts.length;
if (remaining > 0) {
for (let i = 0; i < (remaining >= amount ? amount : remaining); i++) {
setTimeout(() => {
hiddenPosts[i].classList.remove("hidden");
}, 300 * i);
}
} else {
alert('no more posts')
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: scale(0);
}
to {
opacity: 1;
transform: scale(1);
}
}
body {
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
}
.top-news {
padding: 15px 25%;
background: rgba(0, 0, 0, 0.5);
margin: 5px 0;
animation: fadeIn 1s ease;
}
.top-news.hidden {
display: none;
}
<div class="top-news">1</div>
<div class="top-news">2</div>
<div class="top-news">3</div>
<div class="top-news">4</div>
<div class="top-news">5</div>
<div class="top-news hidden">6</div>
<div class="top-news hidden">7</div>
<div class="top-news hidden">8</div>
<div class="top-news hidden">9</div>
<div class="top-news hidden">10</div>
<div class="top-news hidden">11</div>
<button onclick="more()">Load More</button>
Answered By - Alireza
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.