Skip to content

Instantly share code, notes, and snippets.

@anhtran
Created July 23, 2019 08:22
Show Gist options
  • Save anhtran/71a280c978315de27600959c830d7853 to your computer and use it in GitHub Desktop.
Save anhtran/71a280c978315de27600959c830d7853 to your computer and use it in GitHub Desktop.
Implement Bootstrap 4 Toast without injecting HTML
/* Author: Anh Tran <anhtran.net> */
/* Date: 2019-07-23 14:36 */
function showMessage (content, style, title, subTitle, delay=2000) {
const id_ = Date.now()
const body = $('body')
let wrapper = $('#id_message_wrapper')
if (!content) {
return
}
let styleClass = ''
if (style) {
styleClass = `toast-${style}`
}
// language=HTML
if (!wrapper || !wrapper.length > 0) {
wrapper = $('<div id="id_message_wrapper" aria-live="polite" aria-atomic="true" class="d-flex justify-content-center align-items-center flex-column" ' +
'style="position: absolute; top: 0; right: 0; left: 0; padding-top: 20px;"></div>')
body.prepend(wrapper);
}
const html = `<div class="toast ${styleClass}" role="alert" aria-live="assertive" aria-atomic="true" id="${id_}"
style="position: initial;">
<div class="toast-header">
<strong class="mr-auto">${title}</strong>
<small>${subTitle}</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="toast-body">${content}</div></div>`
const html2 = `<div class="toast ${styleClass}" role="alert" aria-live="assertive" aria-atomic="true" id="${id_}" style="position: initial;">
<div class="toast-body">${content}</div></div>`
if (title) {
wrapper.append(html);
} else {
wrapper.append(html2);
}
$('.toast').toast({
autohide: true,
delay: delay
})
const ele = $(`#${id_}`)
ele.toast('show')
ele.on('hidden.bs.toast', function () {
ele.remove()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment