refactor getRandomItem func in toast notification project

pull/57/head
Darbaz Ali 4 years ago
parent 4dd2f9dd57
commit f2d70137ea

@ -1,23 +1,21 @@
const button = document.getElementById('button') const button = document.getElementById('button')
const toasts = document.getElementById('toasts') const toasts = document.getElementById('toasts')
const messages = [ const messages = ['Message One', 'Message Two', 'Message Three', 'Message Four']
'Message One',
'Message Two',
'Message Three',
'Message Four',
]
const types = ['info', 'success', 'error'] const types = ['info', 'success', 'error']
// pick a random item from an array
const getRandomItem = (array) => array[Math.floor(Math.random() * array.length)]
button.addEventListener('click', () => createNotification()) button.addEventListener('click', () => createNotification())
function createNotification(message = null, type = null) { function createNotification(message = null, type = null) {
const notif = document.createElement('div') const notif = document.createElement('div')
notif.classList.add('toast') notif.classList.add('toast')
notif.classList.add(type ? type : getRandomType()) notif.classList.add(type ? type : getRandomItem(types))
notif.innerText = message ? message : getRandomMessage() notif.innerText = message ? message : getRandomItem(messages)
toasts.appendChild(notif) toasts.appendChild(notif)
@ -25,11 +23,3 @@ function createNotification(message = null, type = null) {
notif.remove() notif.remove()
}, 3000) }, 3000)
} }
function getRandomMessage() {
return messages[Math.floor(Math.random() * messages.length)]
}
function getRandomType() {
return types[Math.floor(Math.random() * types.length)]
}
Loading…
Cancel
Save