What is the best way to animate an element when it mounts in Vue?

My current code snippet is as follows...

<template>
  <div class="layered-image fit">
    <img src="/img/Stars-background.svg" class="img1"/>
    <img ref="img2" src="/img/Mo-zen.svg" class="img2" />
  </div>
</template>
<script setup>
import {ref, onMounted} from "vue";
const img2 = ref(null);
onMounted(()=>{
  console.log("Setting the style");
  img2.value.style.bottom = "10%";
})
</script>
<style>
.img1 {
  position: absolute;
  bottom: 0;
  left: calc( 50% - 400px );
}
.img2 {
  position: absolute;
  bottom: 20%;
  transition: bottom 2s linear;
  right: calc( 50% - 280px );
}
.fit {
  height: 100%;
  width:100%;
}
</style>

I am attempting to adjust the image position incrementally from 20% to 10% over a period of 2 seconds once the component is loaded. However, it appears that only setting it to 10% without any smooth transition. How can I achieve the proper transitioning effect for the bottom property?

Answer №1

If you want to master transitions, the key is to refer to the documentation rather than experimenting with pure css unless absolutely necessary. Here is a helpful resource: https://vuejs.org/guide/built-ins/transition.html

In your specific case, it seems like there may be confusion between variables and refs.

As mentioned in this post: Smooth CSS transition from position relative to position absolute with :hover::after

Remember that transitions cannot be applied directly to position properties.

Answer №2

If you are looking to animate two images, I suggest exploring Vue's native GroupTransition feature.

With GroupTransition, you can assign a specific name to your container and utilize Vue's JavaScript hooks for easy implementation.

Here is an example of how you can apply CSS transitions:

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

This code will apply the specified CSS styles to any element within the list container during component enter and exit events.

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

Components within Vue functional components

During my exploration of functional components in Vue, I came across an interesting discovery. It seems that the components property cannot be used to declare sub-components for functional components. Attempting to do so leads to an Unknown custom element ...

Identifying and implementing page language in nextJS: Solving the ReferenceError "window is not defined" issue

I am currently working on developing a website that can automatically detect the user's country and set the language accordingly. In React, I usually achieve this by using window.navigator.language. Here is a snippet of the code: import * as pt from ...

Regular expression to limit a string to a maximum of 5 consecutive numeric characters and a total of up to 8 numeric characters

I need help creating a regex pattern that limits a string to no more than 5 consecutive numeric characters and a total of 8 numeric characters. Here are some examples: 12345 => True Yograj => True Yograj1234 ...

How can I attach a jQuery plugin to a textbox with a changing class name?

I have a function that converts a regular text field into a datepicker: <input type="text" class="datepicker form-control" name="text-150" > var DatePicker = function () { if ($(".datepicker").length === 0) { return; } $(".datepic ...

Waiting for POST request to be executed once data is inserted

This was a new experience for me; I took a break from working on the project for a while, and suddenly all POST routes stopped functioning. However, the GET routes were still working perfectly fine. After extensive debugging, I discovered that removing the ...

Three.js fails to load due to Require.js issue

Having encountered a JavaScript error in browser (on the last line mentioned above) with generated code from TypeScript: define(["require", "exports", "three", "jquery", "./test"], function (require, exports, THREE, jQuery, Test) { var Main = (function () ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

What are the top JavaScript widget libraries for a measurement reporting web application?

Embarking on a new venture to develop a web application tailored for engineers in need of reporting measurements. The key elements that form the backbone of this project include: grids charts maps After thorough research, I have delved into various java ...

I require a breakdown of the JavaScript code, please

Are you struggling with a code snippet that involves CSS, JavaScript, and HTML? Let's take a look at the complete code: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/bo ...

Is there a way to prevent a background video from automatically playing whenever the user navigates back to the home page?

Recently, I was given a design that requires a background video to load on the home page. Although I understand that this goes against best practices, the client has approved the design and now I need to come up with a solution. The video is already in pla ...

Creating a calculator with JQuery and encountering challenges with performing multiple calculations

I've been working on a calculator using jQuery, but I'm encountering issues with the clear button not functioning properly after multiple calculations. On top of that, subsequent calculations are producing inaccurate results. I am seeking to enh ...

The Input element's onChange event is not functioning as expected

I am experiencing some issues with my code. I am trying to dynamically change the background color based on user input, but I am struggling to make it work. It seems like a simple task, so I must be missing something. Below is my HTML markup and jQuery: ...

How can I use Braintree and Javascript to automatically fill in transaction data (such as card and address information) for customers who have made previous purchases?

I have implemented Braintree's Hosted Fields and Javascript for signup and payment processing. While I can successfully send a payment nonce, I am facing an issue with preloading user information from the Braintree portal for users who already have su ...

Verify if there is a cookie available; then execute the load() function. If the cookie matches, it is necessary to

$(document).ready(function() { var hrefs = { "en": ["includes/test1.html", "includes/test2.html"], "es": ["includes/test3.html", "includes/test4.html"] } $(function() { var cookie = Cookies.get('langCookie'); if (cookie) { ...

Enable the Drill Down feature in a Highcharts chart by interacting with a different chart through a manual click

Utilizing Highcharts for creating two charts within Angular (although that detail may not be relevant to the issue at hand) - a pie chart and a bar chart. I have both charts defined and my objective is to initiate a drill-down action in the bar chart upon ...

Unusual predicament encountered while using Flow type validation

I've encountered a puzzling situation in my React app while trying to integrate Flow's typechecking. I'm struggling to make everything work smoothly. Here is the relevant code snippet: // @flow export const UPDATE_SESSION_PROP: string = &ap ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...