toast
snackbar needs different fade out animation (swap). the toast component must merge its options to prevent unwanted behaviour
by Yerko Palma
HTML
<div id="app">
<div id="target">
</div>
<button @click="showToast('some text to try')">
Add toast
</button>
<button @click="showToast('some text to try', {mobile: true})">
Add snackbar
</button>
</div>
CSS
.toast {
width: 100%;
padding: 15px;
position: fixed;
}
.toast.mobile {
padding: 0;
}
.toast-content {
display: flex;
background-color: rgba(0, 0, 0, .3);
padding: 10px;
flex-wrap: wrap;
justify-content: space-between;
font-family: "Gill Sans Extrabold", Helvetica, sans-serif;
top: 20px;
left: auto;
margin: 0 auto;
width: 50%;
margin: 0 auto;
border-radius: 4px;
transition: all 0.3s;
transform: translateY(-100px);
opacity: 0;
box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
}
.toast-content.mobile {
width: 100%;
border-radius: 0;
}
.toast-content.is-shown {
transform: translateY(0px);
opacity: 1;
}
.toast-content.is-falling {
transform: translateY(100px) rotate(30deg);
margin-top: 50px;
opacity: 0;
}
.toast-text {
order: 1;
width: 100%;
text-align: center;
}
.toast-button.mod-close-button {
order: 99;
background-color: transparent;
border: 0;
outline: 0;
align-self: flex-start;
padding: 0;
font-size: 1.4rem;
margin-top: -5px;
position: absolute;
right: 5px;
}
Babel + JSX
const Toast = Vue.extend({
template: `<div :class="{'mobile': options.mobile}" class="toast">
<div :class="{'mobile': options.mobile}" class="toast-content">
<button v-show="!options || options.closeButton" @click="hide" class="toast-button mod-close-button js-hide-toast">×</button>
<p class="toast-text">{{text}}</p>
</div>
</div>`,
ready: function () {
var vm = this
var toast = document.querySelector('.toast-content')
toast.addEventListener('transitionend', function () {
if (toast.classList.contains('is-shown') && toast.classList.contains('is-falling')) {
toast.classList.remove('is-shown')
toast.classList.remove('is-falling')
vm.$destroy(true)
}
})
// used to perform animation
setTimeout(function () {
vm.show()
if (vm.options && !vm.options.closeButton) {
setTimeout(function () {
vm.hide()
}, 2500)
}
}, 0)
},
methods: {
hide: function () {
var toast = document.querySelector('.toast-content')
toast.classList.add('is-falling')
},
show: function () {
var toast = document.querySelector('.toast-content')
toast.classList.add('is-shown')
}
}
})
new Vue({
el: '#app',
data () {
return {
toastType: 'danger'
}
},
methods: {
showToast: function (textInput, options) {
const target = this.$el.querySelector('#target')
if (!target) {
const div = document.createElement('div')
div.setAttribute('id', 'target')
this.$el.insertBefore(div, this.$el.firstChild)
}
const toastComp = new Toast({
el: this.$el.querySelector('#target'),
parent: this,
data () {
return {
text: textInput,
options
}
}
})
}
}
})