Find and clear a toast (Toastr)

Gokul picture Gokul · Dec 8, 2016 · Viewed 20.5k times · Source

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.

Answer

imjosh picture imjosh · Dec 8, 2016
toastr.options = {
    tapToDismiss: false
    , timeOut: 0
    , extendedTimeOut: 0
    , allowHtml: true
    , preventDuplicates: true
    , preventOpenDuplicates: true
    , newestOnTop: true
    , closeButton: true
    , closeHtml: '<button class="btn" style="background-color: grey; padding: 5px;">OK</button>'
}

toastr.warning("You are warned");
toastr.warning("You are warned 2");

https://jsfiddle.net/3ojp762a/3/

Or, to do it the way you were trying, if you need that for some reason:

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

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


$('.close-toastr').on('click', function () {
    toastr.clear($(this).closest('.toast'));
});

https://jsfiddle.net/esgrwznu/