Prepend only once on scroll

Prepend an element on scroll only once if class exist. Remove if class does not exist.

For example scroll down -> class is added + prepend. Scroll back up -> class is removed so is prepend and so on.

$(window).scroll(function() {
if($("#container").hasClass("active")){
     $("#container-wrapper").addClass("active-exists");
     $("#container-wrapper").prepend("<p>Test</p>");
}
else {
     $("#container-wrapper").removeClass("active-exists");
     $("#container-wrapper").remove("<p>Test</p>");
}

});

Current behavior keeps adding infinite <p>Test</p> non stop, just spams it while scrolling up and down.

Answer

You can check this with a flag “appended”

window.appended = false; // set as global variable
$(window).scroll(function() {
   if($("#container").hasClass("active")){
        $("#container-wrapper").addClass("active-exists");
        if (!window.appended){   // check with global variable
             $("#container-wrapper").prepend("<p>Test</p>");
             appended = true;
        }
           
   }
   else {
        $("#container-wrapper").removeClass("active-exists");
        $("#container-wrapper").remove("<p>Test</p>");
    }
}