Experimenting with animating a snackbar in Svelte by incorporating distinct animations for its entrance and exit effects

My current objective is to create a snackbar component with a Material-esque design that will emerge from the bottom of the screen and blur out once dismissed. Here is my current implementation:

<script lang="ts">
    import '../css/snackbar.css';

    import { linear } from 'svelte/easing';
    import { blur, fly } from 'svelte/transition';

    let show = true;

    export let message: string;
    export let actionText: string = 'Dismiss';

    let options = { duration: 350, easing: linear };
</script>

{#if show}
    <div
        class="snackbar"
        class:snackbar-active={Boolean(message)}
        transition:blur={options}
    >
        <div class="snackbar-text">
            {message}
        </div>
        <button class="link" on:click={() => (show = !show)}>{actionText}</button>
    </div>
{:else}
    <div
        class="snackbar"
        class:snackbar-active={Boolean(message)}
        transition:fly={{ ...options, opacity: 1, y: 600 }}
    >
        <div class="snackbar-text">
            {message}
        </div>
        <button class="link" on:click={() => (show = !show)}>{actionText}</button>
    </div>
{/if}

Furthermore, here is the corresponding CSS:

.snackbar {
    align-items: flex-end center;
    background: var(--project-color-surface-variant);
    border-radius: 0.5rem;
    color: #fff;
    display: inline-flex;
    justify-content: flex-end center;
    padding: 0.625rem 1.25rem 0.625rem 1.25rem;
    position: fixed;
    width: fit-content;
    z-index: 9;
}
.snackbar .link {
    background: none;
    border: none;
    color: var(--project-color-secondary);
    display: inline-flex;
    padding-left: 1.25rem;
}

Currently, the snackbar displays at the bottom of the screen, blurs out upon dismissal, then immediately reappears from the top before starting the cycle again if triggered. I aim for it to appear only when activated and disappear permanently upon user interaction.

I've attempted using CSS keyframes for transitions without success. Exploring the built-in Svelte transitions seemed promising, but I still seek a solution tailored to my specific requirements.

Answer №1

Your issue lies in the structure of your if/else statement. It is recommended to have only one branch under the if condition and utilize in: and out: for transition toggling.

{#if show}
    <div
        class="snackbar"
        class:snackbar-active={Boolean(message)}
        in:fly={{ ...options, opacity: 1, y: 600 }}
        out:blur={options}>
        <div class="snackbar-text">
            {message}
        </div>
        <button class="link" on:click={() => (show = !show)}>{actionText}</button>
    </div>
{/if}

Check out this REPL link for reference!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to use Office.context.mailbox.item.displayReplyAllForm with attachments on outlook.live.com as well as receiving internal server errors when using the Outlook API

When using office.js outlook add-ins, the displayReplyAllForm with attachments function is opening the reply form without attachments in outlook.live.com. However, it works perfectly fine in outlook.office.com. Is there any workaround for this issue? Off ...

Selecting multiple rows on a Lazily Loaded jQuery Datatable

Currently, I am utilizing a lazy loaded (Deferred) jQuery Datatable and attempting to implement multi-row selection. However, every time I switch to another page of the datatable, the selected rows from the previous page get cleared. // Here's how yo ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

Re-Rendering Component in React Continuously Keeps Checkbox Checked Event Flowing

I am working on a material ui checkbox formgroup that is generated dynamically based on data received from an API. Essentially, the user is presented with a question and a set of answers. The user checks all the valid answers and clicks 'next'. I ...

Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so: enum AllDirections { TOP = 'top', BOTTOM = 'bottom', LEFT = 'left', RIGHT = 'right', } However, trying to use variab ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

Is it feasible to deduce the generic type of a function by considering all remaining arguments?

I'm working with code that looks like this: type Boxed<T> = { inner: T } const box = <T>(inner: T): Boxed<T> => ({ inner }); function test<T extends Boxed<any>>(...args: T[]): T extends Boxed<infer I> ? I : ne ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

Sending Values to a Function via Datatables Button

Is there a way to pass the value of a button in a datatables to a function? Currently, I am only able to get the value of the first row. Any assistance would be greatly appreciated. All I need is to alert the parameter and I will handle the rest. Here is ...

How to maximize efficiency by utilizing a single function to handle multiple properties in Angular

I have 2 distinct variables: $scope.totalPendingDisplayed = 15; $scope.totalResolvedDisplayed = 15; Each of these variables is connected to different elements using ng-repeat (used for limitTo) When the "Load More" button is clicked (ng-click="loadMore( ...

Using PHP to send JSONP callback responses

Is it possible to achieve "two-way" communication using JSONP and PHP? For example: jQuery / JSONP $.ajax({ url: 'http://server/po.php', cache : false, dataType: 'jsonp', timeout: 30000, type: 'GET', ...

Tips on creating a universal shortcut function for React.js components using decorators

Utilizing React Intl for internationalization requires me to utilize this.props.intl.formatMessage({id: 'some.message.id'}, values) to retrieve a translated string within the render() method. Is there a way to create a decorator that acts as a sh ...

Utilizing Jquery or Javascript to Establish a Fresh Perspective for CylinderGeometry with Three.js

I'm attempting to change the dimensions of a cylinder created using examples from Three.js at runtime, but my code doesn't seem to be working. Here is the code snippet I am using: HTML <script src="http://www.html5canvastutorials.com/librari ...

Remove all child subcategories within the selected (sub)category from a cascading dependent dropdown menu selection

I'm currently working on implementing chained dependent dropdown combobox selection. The idea is to have one combobox for the main category, and once the main category is selected, another <select> will appear for choosing a subcategory, and so ...

Code containing insertAdjacentHTML() does not run as expected due to injection of script

I have a scenario in my application where I am sending a request from the client to a node.js server. The server responds with an HTML containing a script: app.post('/verify', cors(issue2options), async (req, res) => { let auth = await mon ...

Guide: Utilizing JSON API data to generate marker labels on a leaflet map

Users are presented with points to click on. When a point is clicked, a menu displays text information. I have successfully placed the points, but when attempting to retrieve specific data from the database upon clicking a point, it does not show the marke ...

What is the best way to connect an image to a different webpage?

I have a question regarding a div that contains an image acting as a link to another page. The image has text overlaying it and can be found at this link: This code was sourced from the internet, but I made some modifications to it. My goal is simply to ...

Using fit-content with dynamic font size in CSS: How does it work?

Let's take a look at this div element : <div style=" text-align : center; font-size : min(calc(var(--fp-title-font-ratio-h) *100vh),calc(var(--fp-title-font-ratio-w) *100vw)); color ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...