Toasty CSS with BS4

Monday 21 October 2019

Toasty CSS with BS4

In Bootstrap 4 you can have appear small alert-like rectangles, called toasts. However, getting these to work like notifications on top of the page in the top right is not trivial as it requires some CSS trickery. Here is what is required.

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.

Implementation

If you want to see a place where this is implemented just head over to https://michelanglo.sgc.ox.ac.uk as you'll be greeted by one!

No comments:

Post a Comment