Restrict the maximum toast to show

17 Feb 20223 minutes to read

You can restrict the maximum toast count by using the event callback function and terminate the toast displaying process by setting the cancel event property in the beforeOpen event.

The following sample demonstrates restricting toast displaying up to 3. You can restrict by your own count with custom code blocks.

<div class="control-section" style="width:400px;margin:0 auto;">
    <ejs-toast id="element" title="Sample Toast Title" content="Sample Toast content" beforeOpen="onBeforeOpen">
        <e-toast-position X="Center"></e-toast-position>
    </ejs-toast>
    <ejs-button id="showToast" content="Show Toast" cssClass="e-btn"></ejs-button>
</div>
<script type="text/javascript">
    var toasts = [
        { title: 'Warning !', content: 'There was a problem with your network connection.' },
        { title: 'Success !', content: 'Your message has been sent successfully.' },
        { title: 'Error !', content: 'A problem has been occurred while submitting your data.' },
        { title: 'Information !', content: 'Please read the comments carefully.' }
    ];
    var maxCount = 3;
    var toastFlag = 0;
    setTimeout(
        () => {
            var toastObj = document.getElementById('element').ej2_instances[0];
            toastObj.target = document.body;
            toastObj.show(toasts[toastFlag]);
            ++toastFlag;
        }, 1000);
    function onBeforeOpen(e) {
        var toastObj = document.getElementById('element').ej2_instances[0];
        if (maxCount === toastObj.element.childElementCount) {
            e.cancel = true;
        } else {
            e.cancel = false;
        }
    }
    document.getElementById("showToast").addEventListener('click', function () {
        var toastObj = document.getElementById('element').ej2_instances[0];
        toastObj.show(toasts[toastFlag]);
        ++toastFlag;
        if (toastFlag === (toasts.length)) {
            toastFlag = 0;
        }
    });
</script>
public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }
}