Automatically removing after append without binding

–1 vote
asked Sep 12, 2017 by sam

I've created a function that will apply a notification badge to the element I specify, but when I update the badge, I need to remove the last one.

If my notification is 2, when it re-loads I need it to remove the 2 and replace it with 1.

JAVASCRIPT

 function checkNotifications(parent, child, notificationParent){
    $(notificationParent).remove(".right-bar-notification-badge");
    var amount = $(parent+" "+child).length;
    if(amount > 0){
        $(notificationParent).css("position","relative");
        $(notificationParent).append("<div class='right-bar-notification-badge'>"+amount+"</div>");
    }
 }

I know the element has to bind before it can be removed, but what is the best way for me to do this, without having to click or interact with the element?

I basically want it so whenever I call this function, it removes the existing badge and replaces it with another, if there is more than 0 notifications.

Thanks

1 Answer

0 votes
answered Sep 12, 2017 by sam

I ended up using this method

JAVASCRIPT

 function checkNotifications(parent, child, notificationParent){
    $(notificationParent+' .notification-badge-wrapper').html("");
    var amount = $(parent+" "+child).length;
    if(amount > 0){
        $(notificationParent).css("position","relative");
        $(notificationParent).append("<div class='notification-badge-wrapper'><div class='right-bar-notification-badge'>"+amount+"</div></div>");
    }
 }

Appended a wrapper around it each time and emptied the wrapper each time the function was ran. In doing this, if the amount was 0, it never appended the notification badge.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...