Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this?

I considered using a setTimeout function, but I am having trouble implementing it correctly. My code is inspired by this example on CodePen: https://codepen.io/lucasfads/pen/QWwjGjv

<a href="#" class="button" id="specialButton">
  <span class="icon"></span>
  <span class="text">Hakuna Matata</span>
</a>
mounted() {
  document.getElementById("specialButton").classList.add("expanded");

  setTimeout(() => {
    document.getElementById("specialButton").classList.remove("expanded");
  }, 3000);
}
.button {
  background-color: #099;
  color: white;
  text-decoration: none;
  border-radius: 60px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  overflow:hidden;
  width: auto;
  max-width: 32px;
  transition: max-width 0.5s;
}

.button:hover,
.button .expanded {
  max-width: 300px;
}

.icon {
  font-family: "Font Awesome 5 Free";
  font-size: 16px;
  margin-right: 15px;
  padding: 0px 8px;
  display: flex;
  align-items: center;
}

.text {
  white-space: nowrap;
  padding-right: 15px;
}

Answer №1

Kindly review the following snippet (Vue method, no need for element retrieval):

new Vue({
  el: '#demo',
  data() {
    return {
      initBtn: true
    }
  },
  mounted() {
   setTimeout(() => this.initBtn = false, 3000);
  }
})
.button {
  background-color: #099;
  color: white;
  text-decoration: none;
  border-radius: 60px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  overflow:hidden;
  width: auto;
  max-width: 32px;
  transition: max-width 0.5s;
}

.button:hover,
.button.expanded {
  max-width: 300px;
}

.icon {
  font-family: "Font Awesome 5 Free";
  font-size: 16px;
  margin-right: 15px;
  padding: 0px 8px;
  display: flex;
  align-items: center;
}

.text {
  white-space: nowrap;
  padding-right: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <a href="#" class="button" :class="initBtn && 'expanded'">
    <span class="icon"></span>
    <span class="text">Hakuna Matata</span>
  </a>
</div>

Answer №2

The correct syntax should be .button.expanded instead of .button .expanded

In addition, I agree with Jaromanda X's comment that directly manipulating the DOM in Vue is not a recommended practice.

Another idea to consider is setting the class by default and then removing it later for better efficiency. This way, you only need to mount and remove the class, resulting in 2 DOM operations instead of mounting, adding class, and removing class, which would require 3 operations.

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

Is there a reason behind why this functionality is only applicable to a class component and not a functional one?

Essentially, I am working with multiple buttons and aiming for the user to be able to select more than one button at a time. I attempted to achieve this using a functional component by storing the button states as objects with the useState hook. While the ...

Steps for clearing input field with type=date in Protractor:

I am currently working with protractor version 4.0.4 and I'm encountering an issue where I cannot clear a date input field. It seems like Chrome is introducing some extra controls that are causing interference. You can find further details about Chro ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

Guide to make a loading animation button through the use of HTML, CSS, and JavaScript

"Hello, I am currently in the process of working on a project and am interested in implementing a button with a loading animation that can be displayed during actions like form submission or content loading. I'm seeking some advice or code sample ...

Struggling to implement JQuery code in a Next.js application

I'm having trouble getting my tracking code to work in Next.js. <Script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments) } gtag('js', new Date()) ...

generate a series of nested divs within one another

I am looking to create a custom nested loop that will generate div elements based on the content of my h1 and h2/h3 tags. I understand this may have been covered in other inquiries, so any guidance would be appreciated :) Here is the initial HTML: <h1& ...

Passing form values from JavaScript to a JSP page - a comprehensive guide

I am working on a sample HTML page that includes inline JavaScript for calculating geocodes and retrieving latitude and longitude values. My question is, how can I submit all the form values along with the latitude and longitude returned from the showlocat ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

Receiving an inaccurate value from the input with type='number' attribute

There is an input field where users can enter a string, and I need to capture the value entered into it. $("#test").on("change", function(){ console.log($(this).val()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...

Generate a fresh DOM element when a particular height threshold is achieved, utilizing a portion of the previous DOM element's content

Update: 27th December 2016 The heading has been modified because any DOM element can be the target, whether it is a <p> element or not. Additional information has been provided about the tools being used and the desired outcome. Are there nativ ...

Troubleshooting Vue Component Visibility Issue in Laravel 5.4 with Passport Integration

Implementing passport using Laravel 5.4 has been a smooth process following the official documentation step by step. All was going well until I reached the "Frontend Quickstart" section. After executing the command to publish the vendor: php artisan vend ...

Remove dynamically created elements from an AngularJS div

Is there a way to remove an item from the criteria list when clicking the delete button? Currently, only the filter is being refreshed and not the tables. Any suggestions on how to resolve this issue? HTML <ul class="list-unstyled"> <l ...

What could be the reason for the issue `injection "store" not found` showing up when attempting to call `this.store.commit()`?

I am currently working on storing values with VueX, specifically using Vuex 4.0 instead of the older version 3.0. While attempting to commit a value, I encountered an issue as follows: ... this.$store.commit("changerusername", u) ... To addres ...

Can global scope be injected into a class instantiated in ES6, also known as a singleton?

Before I get started, I want to apologize in advance for the lengthy code that is about to follow. It may make this question seem a bit bloated, but I believe it's necessary for understanding my issue. Imagine we have a predefined MainModule: ' ...

In PHP, the hidden input type doesn't always provide true concealment within a form if the value being passed

I am attempting to populate a hidden input field with the value of an XML string generated from an array. However, when I set the hidden field value using the XML string, it is being displayed in the HTML output. Surprisingly, if I use plain text as the va ...

What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to swit ...

The Angular directive was unable to reach the controller located higher up in the DOM hierarchy

template <section id="content" ng-controller="ReservationController as resvnCtrl" > <form role="form" name="resvnCtrl.form"> <div data-date-picker> </div> ...