Search results

Prevent duplicate toast display

You can prevent identical same toast displaying in a screen by the event function and terminate the toast displaying process by setting the cancel event property in the beforeOpen event.

The following sample demonstrates preventing duplicate title toast element displaying with custom code blocks.

Source
Preview
index.js
index.html
ej.base.enableRipple(true);

//Initialize Toast component

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.' },
    ];

var ele = document.createElement("button");
ele.textContent = "Show Toast"
ele.classList.add('e-btn');
ele.id = "show_toast";
document.body.appendChild(ele);
var toastFlag = 0;

var toast = new ej.notifications.Toast({
    title: 'Matt sent you a friend request',
    content: 'You have a new friend request yet to accept',
    target: document.body,
    timeOut:0,
    position: {
        X: 'Center'
    },
    beforeOpen: onBeforeOpen
});

//Render initialized Toast component

toast.appendTo('#element');


toast.appendTo('#element');
toast.show(toasts[toastFlag]);
++toastFlag;
ele.onclick = function () {
  toast.show(toasts[toastFlag]);
  ++toastFlag;
  if (toastFlag === (toasts.length)) {
      toastFlag = 0;
  }
};


function onBeforeOpen(e) {
   e.cancel = preventDuplicate(e);
}

function preventDuplicate(e) {
    var toastEle = e.element;
    var toasts = e.toastObj.element.children;
    for (var i = 0; i < toasts.length; i++) {
        if ((toasts[i]).querySelector('.e-toast-title').isEqualNode(toastEle.querySelector('.e-toast-title'))) {
            return true;
        }
    }
    return false;
}
<!DOCTYPE html><html lang="en"><head>
    <title>Essential JS 2 Toast</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Typescript Toolbar Controls">
    <meta name="author" content="Syncfusion">
    <link href="index.css" rel="stylesheet">
    <link href="//cdn.syncfusion.com/ej2/material.css" rel="stylesheet">
    
    
<script src="//cdn.syncfusion.com/ej2/dist/ej2.min.js" type="text/javascript"></script>
</head>

<body>
    
    <div id="container">
        <div id="element"></div>
        <br><br>
        <div id="result"></div>
        <div id="templateToast" style="display: none;color:red"> System affected by virus !!! </div>
    </div>


<script>
var ele = document.getElementById('container');
if(ele) {
    ele.style.visibility = "visible";
 }   
        </script>
<script src="index.js" type="text/javascript"></script>
</body></html>