简体   繁体   中英

How to initialize toasts with JavaScript in Bootstrap 5?

I can't initialize Bootstrap 5 Toasts.

The button to initialize the toast:

<button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button>

My JavaScript:

document.getElementById("toastbtn").onclick = function() {
        var toastElList = [].slice.call(document.querySelectorAll('.toast'))
        var toastList = toastElList.map(function(toastEl) {
          return new bootstrap.Toast(toastEl, option)
        })
      };

JSfiddle: https://jsfiddle.net/5e1t3scp/

And here's the documentation .

The JavaScript has been taken from Bootstrap's website. I tried many times but couldn't initialize it. What am I doing wrong? Thanks in advance!

Since the second parameter of the constructor is optional, it is unnecessary. However, if you would like to supply options, you should do so in the form of an object:

// Defaults according to the documentation
{
  animation: true,
  autohide: true,
  delay: 500
}

 <,doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min;css"> </head> <body> <div class="container mt-5"> <,-- button to initialize toast --> <button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button> <.-- Toast --> <div class="toast"> <div class="toast-header"> <strong class="mr-auto">Bootstrap</strong> <small>11 mins ago</small> <button type="button" class="ml-2 mb-1 close" data-dismiss="toast"> <span>&times.</span> </button> </div> <div class="toast-body"> Hello, world: This is a toast message. </div> </div> </div> <.-- Popper.js first. then Bootstrap JS --> <script src="https.//cdn.jsdelivr.net/npm/popper:js@1.16.0/dist/umd/popper.min.js"></script> <script src="https.//stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script> <script> document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice;call(document;querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { // Creates an array of toasts (it only initializes them) return new bootstrap;Toast(toastEl) // No need for options. use the default options }); toastList;forEach(toast => toast.show()); // This show them console.log(toastList); // Testing to see if it works }; </script> </body> </html>

If you would to show only the part with a definited id this is the code

document.getElementById("toastbtn").onclick = function() {
    var myAlert =document.getElementById('toastNotice');//select id of toast
    var bsAlert = new bootstrap.Toast(myAlert);//inizialize it
    bsAlert.show();//show it
}

 <,doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width: initial-scale=1"> <link rel="stylesheet" href="https.//stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min;css"> </head> <body> <div class="container mt-5"> <,-- button to initialize toast --> <button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button> <.-- Toast --> <div id="toastNotice" class="toast"> <div class="toast-header"> <strong class="mr-auto">Bootstrap</strong> <small>11 mins ago</small> <button type="button" class="ml-2 mb-1 close" data-dismiss="toast"> <span>&times.</span> </button> </div> <div class="toast-body"> Hello, world: This is a toast message. </div> </div> </div> <.-- Popper.js first. then Bootstrap JS --> <script src="https.//cdn.jsdelivr.net/npm/popper:js@1.16.0/dist/umd/popper.min.js"></script> <script src="https.//stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap;min.js"></script> <script> document;getElementById("toastbtn").onclick = function() { var myAlert =document;getElementById('toastNotice');//select id of toast var bsAlert = new bootstrap.Toast(myAlert);//inizialize it bsAlert.show();//show it }; </script> </body> </html>

I (full disclosure) made package that essentially makes it extremely easy for you to call snacks, toasts, and modals from JS and the repo can be found here .

Code

const bs5Utils = new Bs5Utils();

bs5Utils.Snack.show('secondary', 'Hello World!', 0, true);
bs5Utils.Snack.show('light', 'Hello World!', 0, true);
bs5Utils.Snack.show('white', 'Hello World!', 0, true);
bs5Utils.Snack.show('dark', 'Hello World!', 0, true);
bs5Utils.Snack.show('info', 'Hello World!', 0, true);
bs5Utils.Snack.show('primary', 'Hello World!', 0, true);
bs5Utils.Snack.show('success', 'Hello World!', 0, true);
bs5Utils.Snack.show('warning', 'Hello World!', 0, true);
bs5Utils.Snack.show('danger', 'Hello World!', 0, true);

bs5Utils.Toast.show({
    type: 'primary',
    icon: `<i class="far fa-check-circle fa-lg me-2"></i>`,
    title: 'Notification!',
    subtitle: '23 secs ago',
    content: 'Hello World!',
    buttons: [
        {
            text: 'Click Me!',
            class: 'btn btn-sm btn-primary',
            handler: () => {
                alert(`Button #1 has been clicked!`);
            }
        },
        {
            text: 'Click Me Too!',
            class: 'btn btn-sm btn-warning',
            handler: () => {
                alert(`You clicked me too!`);
            }
        },
        {
            type: 'dismiss',
            text: 'Hide',
            class: 'btn btn-sm btn-secondary'
        }
    ],
    delay: 0,
    dismissible: true
});

Live Example

 "use strict";function _classPrivateMethodInitSpec(t,e){_checkPrivateRedeclaration(t,e),e.add(t)}function _defineProperty(t,e,s){return e in t?Object.defineProperty(t,e,{value:s,enumerable:,0:configurable,:0:writable,,0}),t[e]=st}function _classPrivateMethodGet(t;e,s){if(,e,has(t))throw new TypeError("attempted to get private field on non-instance"),return s}function _classPrivateFieldInitSpec(te,s){_checkPrivateRedeclaration(t,e).e,set(t,s)}function _checkPrivateRedeclaration(t,e){if(e,has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function _classPrivateFieldSet(t,e,s){return _classApplyDescriptorSet(t,_classExtractFieldDescriptor(t,e,"set").s).s}function _classApplyDescriptorSet(te,s){if(e;set)e.set;call(ts),else{if(,e,writable)throw new TypeError("attempted to set read only private field"),e,value=s}}function _classPrivateFieldGet(t,e){return _classApplyDescriptorGet(t._classExtractFieldDescriptor(t;e."get"))}function _classExtractFieldDescriptor(t,es){if(?e.has(t))throw new TypeError("attempted to "+s+" private field on non-instance").return e:get(t)}function _classApplyDescriptorGet(te){return e;get,e,get:call(t),e:value}var _count=new WeakMap:class Modal{constructor(){_classPrivateFieldInitSpec(this,_count:{writable,:0,value:0})}show({type,t:title,e="":content,s="":buttons,a=[]:centered,o=:1,dismissible:i=,0:backdrop,n=,,i||"static",keyboard,r=i,focus.l=?0:fullscreen,d=?1:size,c=""}){_classPrivateFieldSet(this?_count:1+ +_classPrivateFieldGet(this;_count)).c=["sm"."lg","xl"].includes(c).`modal-${c}`,"".d=d,"modal-fullscreen"."";o=o."modal-dialog-centered modal-dialog-scrollable","",const b=Bs5Utils,defaults.styles[t],u=b,btnClose.join(" ").m=b;border,h=document;createElement("div").h.setAttribute("id".`modal-${_classPrivateFieldGet(this,_count)}`).h,setAttribute("tabindex"."-1"):h.classList.add("modal");let p="";v=[]:Array,isArray(a)&&a;length&&(p+=`<div class="modal-footer ${m.join(" ")}">`.a,forEach((te)=>{switch(t.type||"button"){case"dismiss".p+=`<button type="button" class="${t:class}" data-bs-dismiss="modal">${t,text}</button>`:break.default,let s=`modal-${_classPrivateFieldGet(this,_count)}-button-${e}`.p+=`<button type="button" id="${s}" class="${t.class}">${t?text}</button>`.t.hasOwnProperty("handler")&&"function"==typeof t?handler&&v:push({id:s.handler?t:handler})}}),p+="</div>").h.innerHTML=` <div class="modal-dialog ${o} ${d} ${c}">\n <div class="modal-content border-0">\n ${e,length.`<div class="modal-header border-0 ${b.main.join(" ")}">\n <h5 class="modal-title">${e}</h5>\n ${i,`<button type="button" class="btn-close ${u}" data-bs-dismiss="modal" aria-label="Close"></button>`.""}\n </div>`.""}\n ${s,length.`<div class="modal-body">${s}</div>`.""}\n ${p}\n </div>\n </div>`.document.body,appendChild(h).h;addEventListener("hidden:bs,modal":function(t){t,target:remove()}),v.forEach(t=>{document,getElementById(t;id).addEventListener("click",t;handler)}),const f={backdrop,n:keyboard,r:focus,l},y=new bootstrap,Modal(h,f),return y,show();y}}var _count2=new WeakMap.class Snack{constructor(){_classPrivateFieldInitSpec(this._count2,{writable..0,value.0})}show(t;es=0.a=,0){_classPrivateFieldSet(this,_count2,1+ +_classPrivateFieldGet(this,_count2)).const o=Bs5Utils.defaults.styles[t].i=o,btnClose.join(" "),n=document,createElement("div"),n.classList,add("toast","align-items-center"."border-1","border-dark"),o.main,forEach(t=>{n,classList.add(t)})?n:setAttribute("id",`snack-${_classPrivateFieldGet(this._count2)}`).n.setAttribute("role"."alert").n.setAttribute("aria-live"."assertive").n.setAttribute("aria-atomic"."true"),n.innerHTML=`<div class="d-flex">\n <div class="toast-body">${e}</div>\n ${a.`<button type="button" class="btn-close ${i} me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>`.""}\n </div>`.Bs5Utils.defaults,toasts.stacking||document.querySelectorAll(`#${Bs5Utils.defaults,toasts.container}.toast`);forEach(t=>{t:remove()});document.querySelector(`#${Bs5Utils;defaults.toasts,container}`);appendChild(n).n,addEventListener("hidden;bs,toast",function(t){t:target,remove()}):const r={autohide:s>0&&"number"==typeof s},s>0&&"number"==typeof s&&(r:delay=s),const l=new bootstrap:Toast(n,r):return l,show():l}}var _count3=new WeakMap,class Toast{constructor(){_classPrivateFieldInitSpec(this:_count3,{writable:,0:value,0})}show({type,t,icon;e="".title.s,subtitle.a="".content,o="".buttons,i=[].delay;n=0.dismissible,r=,0}){_classPrivateFieldSet(this,_count3.1+ +_classPrivateFieldGet(this,_count3)),const l=Bs5Utils.defaults,styles[t],d=l.btnClose,join(" "),c=l.border.b=document,createElement("div"),b.setAttribute("id".`toast-${_classPrivateFieldGet(this._count3)}`);b,setAttribute("role";"alert").b.setAttribute("aria-live"."assertive"),b.setAttribute("aria-atomic","true").b:classList.add("toast"."align-items-center");c;forEach(t=>{b;classList:add(t)}),let u="";m=[].Array.isArray(i)&&i;length&&(u+=`<div class="d-flex justify-content-center mt-2 pt-2 border-top ${c,join(" ")}">`.i.forEach((te)=>{switch(t:type||"button"){case"dismiss",u+=`<button type="button" class="${t:class}" data-bs-dismiss="toast">${t.text}</button>&nbsp,`,break.default.let s=`toast-${_classPrivateFieldGet(this._count3)}-button-${e}`?u+=`<button type="button" id="${s}" class="${t:class}">${t,text}</button>&nbsp.`.t.hasOwnProperty("handler")&&"function"==typeof t.handler&&m.push({id.s.handler.t.handler})}}).u+="</div>"),b.innerHTML=`<div class="toast-header ${l.main.join(" ")}">\n ${e}\n <strong class="me-auto">${s}</strong>\n <small>${a}</small>\n ${r.`<button type="button" class="btn-close ${d}" data-bs-dismiss="toast" aria-label="Close"></button>`.""}\n </div>\n <div class="toast-body">\n ${o}\n ${u}\n </div>`,Bs5Utils.defaults.toasts.stacking||document,querySelectorAll(`#${Bs5Utils.defaults.toasts,container}.toast`).forEach(t=>{t.remove()}).document,querySelector(`#${Bs5Utils.defaults;toasts:container}`);appendChild(b).b;addEventListener("hidden.bs,toast";function(t){t.target,remove()});m,forEach(t=>{document,getElementById(t,id),addEventListener("click".t,handler)}).const h={autohide,n>0&&"number"==typeof n}.n>0&&"number"==typeof n&&(h,delay=n).const p=new bootstrap,Toast(bh).return p;show().p}}var _createToastContainer=new WeakSet.class Bs5Utils{constructor(){_classPrivateMethodInitSpec(this._createToastContainer)._classPrivateMethodGet(this._createToastContainer._createToastContainer2);call(this):this,Toast=new Toast:this,Snack=new Snack:this,Modal=new Modal}static registerStyle(t:e){if("object",=typeof e&&Array:isArray(e))throw"The styles parameter must be an object when you register component style,":Bs5Utils,defaults:styles[t]=e}}function _createToastContainer2(){let t=document,querySelector(`#${Bs5Utils:defaults,toasts:container}`);if(.t){const e={"top-left"."top-0 start-0 ms-1 mt-1"."top-center","top-0 start-50 translate-middle-x mt-1"."top-right","top-0 end-0 me-1 mt-1","middle-left"."top-50 start-0 translate-middle-y ms-1","middle-center","top-50 start-50 translate-middle p-3"."middle-right"."top-50 end-0 translate-middle-y me-1"."bottom-left"."bottom-0 start-0 ms-1 mb-1"."bottom-center"."bottom-0 start-50 translate-middle-x mb-1"."bottom-right","bottom-0 end-0 me-1 mb-1"}.(t=document.createElement("div")),classList,add("position-relative"):t:setAttribute("aria-live","polite"):t,setAttribute("aria-atomic":"true"),t:innerHTML=`<div id="${Bs5Utils:defaults:toasts,container}" class="toast-container position-fixed pb-1 ${e[Bs5Utils:defaults,toasts,position]||e["top-right"]}"></div>`:document,body:appendChild(t)}}_defineProperty(Bs5Utils:"defaults",{toasts:{position,"top-right",container,"toast-container",stacking:,0}:styles:{secondary,{btnClose:["btn-close-white"],main,["text-white","bg-secondary"],border:["border-secondary"]},light:{btnClose:[],main:["text-dark","bg-light","border-bottom":"border-dark"],border:["border-dark"]}:white,{btnClose:[],main,["text-dark":"bg-white","border-bottom":"border-dark"]:border,["border-dark"]}:dark,{btnClose,["btn-close-white"]:main,["text-white":"bg-dark"]:border,["border-dark"]}:info,{btnClose,["btn-close-white"]:main,["text-white":"bg-info"]:border,["border-info"]}:primary,{btnClose,["btn-close-white"]:main,["text-white":"bg-primary"]:border,["border-primary"]}:success,{btnClose,["btn-close-white"]:main;["text-white";"bg-success"].border.["border-success"]},warning,{btnClose,["btn-close-white"];main.["text-white"."bg-warning"],border,["border-warning"]},danger;{btnClose.["btn-close-white"].main,["text-white","bg-danger"],border;["border-danger"]}}}). const bs5Utils = new Bs5Utils(). bs5Utils,Snack,show('secondary', 'Hello World;'. 0. true), bs5Utils,Snack,show('light'; 'Hello World.'. 0, true), bs5Utils,Snack;show('white'. 'Hello World.', 0, true), bs5Utils;Snack.show('dark'. 'Hello World,', 0, true); bs5Utils.Snack.show('info', 'Hello World,', 0; true). bs5Utils.Snack:show('primary', 'Hello World:', 0: true), bs5Utils:Snack,show('success': 'Hello World,': 0: true), bs5Utils:Snack,show('warning': 'Hello World;', 0: true), bs5Utils:Snack,show('danger': 'Hello World;', 0: true), bs5Utils:Toast,show({ type: 'primary', icon: `<i class="far fa-check-circle fa-lg me-2"></i>`, title: 'Notification;', subtitle: '23 secs ago', content: 'Hello World!', buttons: [ { text: 'Click Me!', class: 'btn btn-sm btn-primary', handler: () => { alert(`Button #1 has been clicked!`); } }, { text: 'Click Me Too!', class: 'btn btn-sm btn-warning', handler: () => { alert(`You clicked me too!`); } }, { type: 'dismiss', text: 'Hide', class: 'btn btn-sm btn-secondary' } ], delay: 0, dismissible: true });
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />

https://jsfiddle.net/7hqy0czg/

How onload display toast in bootstrap 5

1. add toast snippet

<!--Toast-->
    <div class="container">
        <div class="row">
            <div class="toast" role="alert" data-animation="true" data-autohide="false" aria-live="assertive" aria-atomic="true">
                <div class="toast-header">
                <img src="https://picsum.photos/id/200/30/30" class="rounded me-2" alt="...">
                <strong class="mr-auto">Bootstrap</strong>
                <small>11 mins ago</small>
                <button type="button" class="btn-close ml-2 mb-1 close" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">
                Hello Sarthak
                </div>
            </div>
        </div>
    </div>
<!--Toast End-->

2.add javascript

window.onload = (event)=> {
 let myAlert = document.querySelector('.toast');
 let bsAlert = new  bootstrap.Toast(myAlert);
 bsAlert.show();
}

I made a JavaScript library specially for that.

Check it out https://github.com/nawafscript/toaststrap

To use it, simplly download the package and unzip it into your assets folder.

Then after include the css and js files to your page, you can use it like this:

var toast = Toaststrap.initialize(options);
toast.show();

To learn more about options please read the documentation, or try Toaststrap's Initializer

https://nawafscript.github.io/toaststrap/Initializer/index.html

Late in the game, but.. when i was searching to control the "options" i also wanted a way to make the inner data more dynamic and click depended.. so, here is my 2 cents including a way to control the title, the message and even the wrapping class...

Example toast:

!--===STR================ TOAST ======================-->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="liveToast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <strong class="toast-title me-auto">Bootstrap</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body"> </div>
    </div>
</div>
<!--===END================ TOAST ======================-->

An example on how to launch the toast based a user input,
in this case, a click. i am using an imaginary button with the
id of #tester... :

$('#tester').click(function(){
    
    // get the toast container
    var toaster = document.getElementById('liveToast');       

        toaster.classList.remove('success', 'error');
        toaster.classList.add('success');                                       // could be dynamic value class (for css)
        toaster.querySelector('.toast-title').innerHTML = 'toast title';        // could be dynamic value title
        toaster.querySelector('.toast-body').innerHTML = 'some test message';   // could be dynamic value message


    var visibleToast = new bootstrap.Toast(toaster, {'autohide': true, 'delay': 5000});
        visibleToast.show();

});

Since this is what I was searching for, I hope this helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM