DEV Community

Designyff
Designyff

Posted on • Originally published at designyff.com

Simple dark snackbar - A step-by-step guide

Snackbar

Tutorial on how to create a simple snackbar that disappears in 3 seconds.

HTML

For HTML, we need a button that will open the snackbar and a div element with id "snackbar" with snackbar text inside.

<button onclick="openSnackbar()">Open snackbar</button>
<div id="snackbar">
    <span>Snackbar text...</span>
</div>
Enter fullscreen mode Exit fullscreen mode

Javascript

With javascript, we'll open and close our snackbar, by adding a class called "active" to a "#snackbar" div element on button click.

We'll simply store select element by id "snackbar" and add a class "active" to it.

After 3 seconds, we'll remove that class, using the "setTimeout()" method.

function openSnackbar() {
    let snackbar = document.getElementById('snackbar')

    // Activate snackbar
    snackbar.classList.add('active')

    setTimeout(() => {
        // Deactivate snackbar (after 3000ms - 3 seconds)
        snackbar.classList.remove('active')
    }, 3000);
}
Enter fullscreen mode Exit fullscreen mode

CSS

For CSS, first we'll style the #snackbar.

We'll set position to absolute with bottom to 0 and left to 50%. With transform translateX set to -50%, this element will be positioned at the bottom of the screen in the middle.

We'll add a little margin and paddings.

Now we'll set background color to dark gray and color to pink.

We'll set snackbar's width to 200px and add a little border radius.

Lastly, we'll hide this element by setting display property to none.

#snackbar {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    margin: 10px;
    background-color: #333;
    padding: 10px 20px;
    width: 200px;
    border-radius: 5px;
    color: rgb(249, 129, 129);
    display: none;
}
Enter fullscreen mode Exit fullscreen mode

Now we'll style the "active" class. This class will be added to our snackbar element when it should be displayed.

To achieve that, we'll overwrite the display property and set it to block.

Don't forget to add the "!important" rule, otherwise it won't be overrode since the id selectors have a higher specificity.

.active {
    display: block !important;
}
Enter fullscreen mode Exit fullscreen mode

And that's it.

You can find full code with video tutorial here.

Thanks for reading. ❤️

Top comments (0)