Prevent duplicate toast display
17 Feb 20225 minutes to read
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.
<div class="control-section" style="width:400px;margin:0 auto;">
@Html.EJS().Toast("element").Title("Sample Toast Title").Position(p => p.X("Center")).Content("Sample Toast content").BeforeOpen("onBeforeOpen").Close("onClose").Created("onCreate").Render()
@Html.EJS().Button("showToast").Content("Show Toast").CssClass("e-btn").Render()
</div>
<script type="text/javascript">
var toasts = [
{ title: 'Warning !', content: 'There was a problem with your network connection.', isOpen: false },
{ title: 'Success !', content: 'Your message has been sent successfully.', isOpen: false },
{ title: 'Error !', content: 'A problem has been occurred while submitting your data.', isOpen: false }
];
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) {
if (preventDuplicate(e)) {
e.cancel = true;
}
}
function preventDuplicate(e) {
var toastEle = e.element;
var toasts = e.toastObj.element.children;
for (var i = 0; i < toasts.length; i++) {
if (toasts[i].title === e.options.title && !toasts[i].isOpen) {
toasts[i].isOpen = true;
return false;
}
}
return true;
}
function onCreate() {
toasts.show(toasts[toastFlag]);
++toastFlag;
}
function onClose(e) {
for (let i: number = 0; i < toasts.length; i++) {
if (toasts[i].title === e.options.title) {
toasts[i].isOpen = 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();
}
}