I’m building a feature where it tells a reader that they’ve already read a specific post. To do this, I need to to notify the user, and I’m doing so by appending an element to an .article. The problem I’m having, is that because I’m appending inside an .each loop, the element is appending 4 times.
Heres my code:
$('.article-container').each(function() {
// CHECK IF THE DATA IS IN THE ARRAY
if(cookieValue.indexOf($(this).data('id')) != -1) {
$(this).addClass('readit');
$('<h4 class="readit-alert">You've read it!</h4>').appendTo('.article-container.readit');
} else {
// OTHERWISE, ADD CLASS NOT READ
$(this).addClass('notread');
}
});
And here is what it’s returning:
<h4 class="readit-alert">You've read it!</h4>
<h4 class="readit-alert">You've read it!</h4>
<h4 class="readit-alert">You've read it!</h4>
<h4 class="readit-alert">You've read it!</h4>
How can write this to only append the “readit-alert” only once within the article-container?
Add
return false;after the append if you want to stop the loop executing.Otherwise, have a global
var appended = false;outside the function, then set it totrueonce you’ve appended it.That is: