DEV Community

Cover image for Create a toast alert using only HTML, CSS, and Javascript
Ashutosh Tiwari
Ashutosh Tiwari

Posted on • Originally published at incoderweb.blogspot.com

Create a toast alert using only HTML, CSS, and Javascript

Hello friends, today in this blog, you will learn how to create a toast alert using only HTML, CSS, and Javascript. In our previous blog, we saw how to create a restaurant menu card design with a filter option using React JS. Earlier, I shared many projects related to javascript, you can check if you want, and don't forget to check HTML, CSS, and Javascript projects.

What is toast alert?

A notification is a message, email, icon, or another symbol that appears when an application wants you to pay attention. The notifications are a method to let you know that something new has happened. The notifications are a method to let you know that something new has happened so you don’t miss anything that might be worth your attention and appears whether you are using an application or not. And an alert notification appears when an application wants to warn you about something.

You may like these:

In this program [Toast Alert Notification], at first, on the webpage, there is a button only but when you click on that button then the alert notification appears on the right top corner. This notification hides automatically after five seconds and there is also a cross-sign button to hide that notification.

There are some options to select, what type of alert you want to show like you have selected warning toast alert, and there is an option to add toast message when you type something that will be shown in the toast message but if you leave the textarea blank then an error alert will be shown.

If you like this blog and want to get the source codes, I have provided all the codes of this program below and I’ve also provided the download link of this program where you can easily download the source files of this program.

The Preview is available here.

HTML Code

<!-- --------------------- Created By InCoder ----------------------->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Toast Alert - InCoder</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
</head>

<body>
    <div class="optionsWrapper">
        <div class="selectOption">
            <p>Select Type</p>
            <select id="toastType">
                <option value="success">Success</option>
                <option value="error">Error</option>
                <option value="warning">Warning</option>
                <option value="info">Information</option>
            </select>
        </div>
        <p>Enter Toast Message</p>
        <textarea placeholder="Toast message" id="toastMessage" cols="30" rows="5"></textarea>
        <button class="btn">Show Alert</button>
    </div>


    <script src="toast.js"></script>
    <script src="script.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

CSS Code

/* --------------------- Created By InCoder --------------------- */

@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body{
    display: flex;
    height: 100vh;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    background-color: #4a43be;
}

.btn {
    width: 8rem;
    display: grid;
    height: 2.5rem;
    font-size: 1rem;
    cursor: pointer;
    color: #4a43be;
    place-items: center;
    border-radius: .4rem;
    transition: all 300ms;
    border: 2px solid #4a43be;
    background-color: transparent;
}

.btn:hover {
    color: #fff;
    background-color: #4a43be;
}

.toast-container {
    position: fixed;
    top: 0;
    right: 0;
    display: flex;
    flex-direction: column;
    margin: 1rem;
}

.toast-container .inAlert{
    display: flex;
    min-height: 3rem;
    min-width: 18rem;
    max-width: 24rem;
    align-items: center;
    padding: .5rem .5rem;
    border-radius: .4rem;
    transform: translateX(25rem);
    justify-content: space-between;
    color: rgb(255 255 255 / 80%);
    transition: transform .5s cubic-bezier(0.24, 0.91, 0.62, 1.24);
}

.toast-container .inAlert.slide-in {
    transform: translateX(0rem);
}

.toast-container .inAlert.error .icon i {
    content: '\f058';
}

.toast-container .inAlert.error {
    background-color: rgb(226 45 59 / 80%)
}

.toast-container .inAlert.success {
    background-color: rgb(43 198 111 / 80%)
}

.toast-container .inAlert.info {
    background-color: rgb(25 140 146 / 80%)
}

.toast-container .inAlert.warning {
    background-color: rgb(214 175 12 / 80%)
}

.toast-container i {
    font-size: 1.5rem;
    margin:  0 .5rem;
    color: rgb(255 255 255 / 80%)
}

.toast-container .inAlert .wrapper{
    display: flex;
    align-items: center;
}

.toast-container .inAlert .wrapper .title {
    text-transform: capitalize;
}

.toast-container .inAlert .closeAlert {
    cursor: pointer;
}

.toast-container .inAlert .wrapper .message {
    font-size: .8rem;
}

.optionsWrapper{
    width: 20rem;
    padding: .5rem .5rem;
    border-radius: .4rem;
    background-color: #fff;
}

.optionsWrapper .selectOption {
    margin-bottom: .6rem;
}

.optionsWrapper p {
    font-size: .9rem;
    font-weight: 500;
}

.optionsWrapper select,
.optionsWrapper textarea {
    width: 100%;
}

.optionsWrapper select{
    height: 2rem;
    padding: 0 .2rem;
    border-radius: .3rem;
}

.optionsWrapper textarea {
    outline: none;
    padding: .2rem;
    border-radius: .3rem
}

.optionsWrapper textarea:focus{
    border: 2px solid #4a43be;
}
Enter fullscreen mode Exit fullscreen mode

Javascript Code

const showAlert = (data) => {
    let { type, message } = data
    let autoClose
    data.autoClose == undefined ? autoClose = 3000 : autoClose = data.autoClose 

    let toastContainer = document.createElement('div')
    toastContainer.classList.add('toast-container')
    var container = document.querySelector('.toast-container')
    if (typeof (container) != 'undefined' && container != null) return
    document.body.appendChild(toastContainer)
    let icon
    if(type == 'error') {
        icon = 'fa-circle-exclamation'
    } else if(type == 'success'){
        icon = 'fa-circle-check'
    } else if(type == 'warning'){
        icon = 'fa-triangle-exclamation'
    } else if(type == 'info'){
        icon = 'fa-circle-info'
    }

    let alert = `<div class="inAlert ${type}">
                    <div class="wrapper">
                        <div class="icon">
                        <i class="fa-solid ${icon}"></i>
                        </div>
                        <div class="details">
                            <div class="title">${type}</div>
                            <div class="message">${message}</div>
                        </div>
                    </div>
                    <i class="fa-solid fa-xmark closeAlert"></i>
                </div>`
    toastContainer.insertAdjacentHTML('afterbegin', alert)
    setTimeout(() => {
        var isAlert = document.querySelector('.inAlert')
        if (typeof (isAlert) != 'undefined' && isAlert != null) isAlert.classList.add('slide-in')
    }, 100)

    setTimeout(() => {
        var isAlert = document.querySelector('.inAlert')
        if (typeof (isAlert) != 'undefined' && isAlert != null) isAlert.classList.remove('slide-in')
        setTimeout(() => {
            document.querySelector('.inAlert').remove()
            removeToast()
        }, 100)
    }, autoClose)

    let closeBtn = document.querySelector('.closeAlert')
    closeBtn.addEventListener('click', () => {
        document.querySelector('.inAlert').classList.remove('slide-in')
        setTimeout(() => {
            document.querySelector('.inAlert').remove()
            removeToast()
        }, 100)
    })
}

const removeToast = () => {
    var container = document.querySelector('.toast-container')
    if (!container.hasChildNodes()) container.remove()
}

let btn = document.querySelector('.btn')

btn.addEventListener('click', () => {
    let toastType = document.querySelector('#toastType').value
    let toastMessage = document.querySelector('#toastMessage').value.trim()
    if(toastMessage == '') showAlert({
        type: 'error',
        message: 'Toast Message cannot be empty',
    })

    showAlert({
        type: toastType,
        message: toastMessage,
    })
})
Enter fullscreen mode Exit fullscreen mode

Latest comments (4)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Cool now add some syntax highlighting to your code blocks it will become more readable πŸ™‚

Collapse
 
incoderweb profile image
Ashutosh Tiwari

Thanks for giving me suggestion.

Collapse
 
vpgmackan profile image
Mackan

That looks really good. Great work!

Collapse
 
incoderweb profile image
Ashutosh Tiwari

Thank you so much😊😊.