javascriptjqueryangularjstoastrangular-toastr

Find and clear a toast (Toastr)


I have a page where there may be multiple toasts added dynamically using the plugin https://github.com/CodeSeven/toastr.

I have a link(Ok) on each toast on clicking that link I need to close only the particular toast not all toast that are visible.

toastr.warning("You are warned. <br/> <a id='close-toastr'> Ok </a>", {
    tapToDismiss: false
    , timeOut: 0
    , extendedTimeOut: 0
    , allowHtml: true
    , preventDuplicates: true
    , preventOpenDuplicates: true
    , newestOnTop: true
});

$('body').on('click', 'a#close-toastr', function () 
    toastr.clear();
});

In the above code I have used toastr.clear() method which clears all toasts.

Can anyone help me how to identify the toast of the Ok link clicked and clear only that toast?

Update #1:

I tried the answer given by @imjosh but, $(this).closest('.toast') finds the correct toast but toastr.clear($(this).closest('.toast')); doesn't close any toast.

If I store the toast object in a variable and pass as an argument to toastr.clear() it works. But, I don't know how to handle multiple toasts this way.

var toast = toastr.warning("You are warned. <br/> <a id='close-toastr'> Ok </a>", {
    tapToDismiss: false
    , timeOut: 0
    , extendedTimeOut: 0
    , allowHtml: true
    , preventDuplicates: true
    , preventOpenDuplicates: true
    , newestOnTop: true
});

$('body').on('click', 'a#close-toastr', function () 
    toastr.clear(toast);
});

Update #2:

Sorry, I am using https://github.com/Foxandxss/angular-toastr plugin not the one I mentioned above.

Thanks.


Solution

  • The answer given by @imjosh works good in normal toastr plugin but not in angular-toastr plugin.

    So, I have tried to use jquery remove() method instead of toastr.clear() method as below and it works good.

    $('body').on('click', 'a#close-toastr', function () {
        $(this).closest('.toast').remove();
    });
    

    Please comment if this way of removing toast produces any issue, but I haven't found any issue with this.

    Finally, Thanks @imjosh for giving me the method to find the closest toast.