Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Only Once Inside an .Each Loop

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&apos;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&apos;ve read it!</h4>
<h4 class="readit-alert">You&apos;ve read it!</h4>
<h4 class="readit-alert">You&apos;ve read it!</h4>
<h4 class="readit-alert">You&apos;ve read it!</h4>

How can write this to only append the "readit-alert" only once within the article-container?

like image 340
onestepcreative Avatar asked Mar 08 '26 02:03

onestepcreative


1 Answers

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 to true once you've appended it.

That is:

var appended = false;

$('.article-container').each(function() {

    // CHECK IF THE DATA IS IN THE ARRAY    
    if(cookieValue.indexOf($(this).data('id')) != -1) {                     

        $(this).addClass('readit');   

        if (!appended){                                      
                $('<h4 class="readit-alert">You&apos;ve read it!</h4>').appendTo('.article-container.readit');
                appended = true;
        }
    } else {

        // OTHERWISE, ADD CLASS NOT READ                
        $(this).addClass('notread');                                        

    }

});
like image 168
Jay Avatar answered Mar 10 '26 16:03

Jay