JavaScript fade effects toggle

Do you have a question?

In Vue.js, achieving the fade in / fade out effect can be easily done by specifying it through the component.

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button v-on:click="show = !show">
    Toggle
  </button>
  <transition name="fade">
    <p v-if="show">hello</p>
  </transition>
</div>

Have you ever wondered how to achieve this effect without using the transition component directly?

I've experimented with it myself multiple times, but I'm facing challenges, and all my search results provide jQuery examples only.

If you know how to do it, please share your knowledge!

Answer №1

When working with Vue, instead of utilizing the <transition> element, you can achieve the same effect through binding with :class

new Vue({
  el: '#demo',
  data: {
    show: true
  }
})
.item {
  transition: opacity .5s;
  opacity: 0;
}

.is-active {
  opacity: 1;
}
<div id="demo">
  <button @click="show = !show">Toggle</button>
  <div class="item" :class="{'is-active' : show}">hello</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

If you were using JavaScript, classList.toggle() would be the way to go:

const toggleTarget = (evt) =>  {
  const selector = evt.currentTarget.dataset.toggle;
  document.querySelectorAll(selector)
    .forEach(EL => EL.classList.toggle("u-transparent"));
};

document.querySelectorAll("[data-toggle]")
  .forEach(EL => EL.addEventListener("click", toggleTarget));
.item {
  transition: opacity .5s;
}

/* UTILITY CLASSES, ATOMS */

.u-transparent {
  opacity: 0;
}
<button data-toggle="#item_1">Toggle</button>
<div id="item_1" class="item">hello</div>

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

Establishing the primary language on a multi-language website

I am currently in the process of developing a website and I intend to offer support for both English and French languages. Up to this point, I've been following the primary solution outlined in this question: How to localize a simple HTML website pag ...

When changing recipients in Firebase, the Javascript code fetches the same message multiple times even though there is only a single message stored in the database

In the process of developing a chat application using Firebase and JavaScript, I have come across an issue. Whenever I switch receivers multiple times, the message I send is fetched multiple times even though it is only sent once to the database. var selec ...

Transforming React Arrays into Objects

I am brand new to React and I'm currently receiving a response from a JSON file that looks like this: methodTypes = ["BOTH","INSIDE","OUTSIDE"] outputTypes = ["STANDARD","DETAILED","ALL_ATTRIBUTES_STANDARD","ALL_ATTRIBUTES_DETAILED"] My goal is to t ...

Updating the Position of an Element in ElectronJS (e.g. Button, Label, etc)

Is there a way to change the positioning of a button in a window using JavaScript and Electron? I am trying to create new input boxes next to existing ones, but they always appear below the last one created. Is it possible to specify x and y coordinates fo ...

Why is my client-side code being compiled and executed on the Node.js backend?

As a newcomer to SSR, I'm not sure if my problem and solution align with standard practices, but it seems unlikely. My objective is to create a dynamic page that allows users to add/remove items. Initially, I developed this component for a client-sid ...

How can I access properties of generic types in TypeScript?

Converting the generic type to any is a valid approach (The type E could be a typescript type, class, or interface) of various entities like Product, Post, Todo, Customer, etc.: function test<E>(o:E):string { return (o as any)['property' ...

I encountered an issue when trying to dynamically add a text field in Angular 2. The error message received was "ERROR TypeError: Cannot read property '0' of

I am currently utilizing Angular2 in my project, and I am attempting to dynamically add a text field. However, I keep encountering an error: Error Message (TS): ngOnInit() { this.myForm = this._fb.group({ myArray: this._fb.array([ ...

choose a selection hopscotch

Is there a way to prevent the input field from jumping out of alignment when an option is selected in these q-select inputs? I want to fix this issue so that the field remains in line with the horizontal alignment. https://codepen.io/kiggs1881/pen/RwENYEX ...

Creating a dynamic visual experience with Angular 2: How to implement multiple font colors

I have a text area which is connected to one string, with the default text color set to white. <textarea style="background-color: black;color:#fff;" [(ngModel)]="outputText"></textarea> The connected string contains multiple variables. retur ...

A guide on tapping into the creation event of an express session

Is there a way to determine when express creates a new session? Specifically, I am utilizing a mongodb session store. I have been encountering an problem related to multiple sessions being generated and I would like to identify the root cause by monitorin ...

Using $eval in Angular to pass a string to an object

Here's the scenario: "var jsonData={first:{name:'John', age:30}};" I am looking to instantiate an object from this string, The standard JS eval function works perfectly for this purpose, however, when attempting to use $eval I encounter ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

The click function is a member of an object within an emit event

I stumbled upon the code snippet below, which triggers the notification-alert event and passes an object as a parameter. this.$root.$emit('notification-alert', { text, type: 'warning', click: () = ...

Selenium web driver showcases its capability by successfully launching the Firefox browser, yet encounters an issue with an invalid address

WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("Selenium WebDriver"); searchElement.submit(); Displays "Search Results" public static void main(String[] args) { // TODO Auto-generated method st ...

Laravel websocket notification causes Vue.js component to stop updating

I'm attempting to update the notification list in real-time, but the Vue component in view is not refreshing. Here's my current code: app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('notificati ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

Is there a method in Next.js for relocating the .env file to a location external to the application folder?

Currently, I am developing a project that incorporates a Next.js application with the .env file stored in the root directory of the project. Is there a way to configure Next.js to search for the .env file in a location other than the app's root folde ...

`I am unable to insert an image into PrimeReact`

I am struggling to integrate images into the dashboard using primereact. Despite placing my photo folder in the public directory and entering the correct photo path, the image is not displaying on the page. I have attempted numerous methods but have been ...

Ionic Vue is throwing an error indicating that a property is not found on the type '{ $route(currentRoute: any): void; }'

Currently, I am developing an Ionic WebApp using Vue and TypeScript. My current task involves retrieving the current id parsed by the route. To achieve this, I have been working on a watcher: export default { data() { return { ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...