First the toast needs to be in a div element whose position is absolute. However, this element need to follow the screen: we want the toast to appear at the top of the window, not the top of the page. Consequently, we need two nested divs at the top of the body element to hold the toast.
<div id="toasterOuter" class="position-absolute m-0 w-100" style="z-index: 9999;">
<div id="toaster" class="m-0 w-100 d-flex flex-column pt-3 pl-3" style="position: fixed;"></div>
</div>
The inner component is of the Bootstrap d-flex and flex-column classes. This means that its children will be forced to be full width and will stack.
Now we can add via JavaScript new toasts as we please to this toaster using a fuction such as this:
window.addToast = (title, body, bg, id, delay) => {
id = id || 'T'+Date.now(); // no id? add a random one
bg = bg || ''; //nothing is white.
if (delay === undefined) delay = 2000;
if (autohide === undefined) autohide = true;
$('#'+id).detach(); //duplicate id??!
$('#toaster').append(``<div class="toast ml-auto w-100 ${bg}" role="alert"
aria-live="assertive" aria-atomic="true"
id="${id}" data-delay=${delay} data-autohide="${autohide}">
<div class="toast-header">
<strong class="mr-auto">${toast_title}</strong>
<small>${toast_time}</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
${toast_body}
</div>
</div>`);
$('#'+id).toast('show');
};
To add a toast with this we can simply call addToast(title:str,body:str,backgroundClass:str,id:str,timeDelay:int)
where the id, time, and background (bg-success, etc) is optional.
No comments:
Post a Comment