I desire to incorporate a subtle fading effect into the script

I have written the script code and now I am looking to add a fade effect to it. Can anyone guide me on how to achieve this? Your help is much appreciated!

※I used an online translator as English is not my native language. Please bear with any awkward phrasing in my message.

const toggleBtn = document.querySelector('.btn');
const activeOn = document.querySelector('#wrap');

toggleBtn.addEventListener('click', () => {
  activeOn.classList.toggle('active');
});
a {
  color: black;
  text-decoration: none;
}

.btn {
  display: inline-block;
  font-size: 20px;
  font-weight: 600;
}

#wrap {
  position: relative;
  display: none;
}

#wrap.active {
  display: block;
}

.contents {
  position: relative;
  display: inline-block;
  margin: 15px;
  padding: 30px;
  border: 1px solid #555;
}
<a class="btn" href="#none">Click</a>

<div id="wrap">
  <div class="contents">
    Active Contents!
  </div>
</div>

Answer №1

To create a smooth fade effect, utilizing CSS transitions is highly recommended.

It's important to keep in mind that CSS transitions may not function properly when toggling between display: block and display: none. In such cases, it's advised to use attributes like visibility or opacity.

Below is the functional code snippet:

const toggleBtn = document.querySelector('.btn');
const activeOn = document.querySelector('#wrap');

toggleBtn.addEventListener('click', () => {
  activeOn.classList.toggle('active');
});
a {
  color: black;
  text-decoration: none;
}

.btn {
  display: inline-block;
  font-size: 20px;
  font-weight: 600;
}

#wrap {
  position: relative;
  opacity: 0;
  transition: opacity 0.5s linear;
  height: 0; /* add this if you want it to take no space */
}

#wrap.active {
  opacity: 1;
}

.contents {
  position: relative;
  display: inline-block;
  margin: 15px;
  padding: 30px;
  border: 1px solid #555;
}
<a class="btn" href="#none">Click</a>

<div id="wrap">
  <div class="contents">
    Active Contents!
  </div>
</div>

Answer №2

To achieve this effect, you can utilize the CSS property opacity instead of using display. Here is an example that demonstrates how to do so:

const toggleBtn = document.querySelector('.btn');
const activeOn = document.querySelector('#wrap');

toggleBtn.addEventListener('click', () => {
    activeOn.classList.toggle('active');
});
a {
    color: black;
    text-decoration: none;
}

.btn {
    display: inline-block;
    font-size: 20px;
    font-weight: 600;
}

#wrap {
    position: relative;
    opacity: 0;
    transition: opacity 1s; 
}

#wrap.active { 
    opacity: 1;
    transition: opacity 1s;
}

.contents {
    position: relative;
    display: inline-block;
    margin: 15px;
    padding: 30px;
    border: 1px solid #555;
}
<a class="btn" href="#none">Click</a>

    <div id="wrap">
        <div class="contents">
            Active Contents!
        </div>
    </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

Error message: "Unexpected token" encountered while using the three.js GLTFLoader() function

I have a requirement to load a .glb model into three.js by using the GLTFLoader. I was able to successfully create a rotating 3D mesh on a canvas without encountering any errors in the console. However, when I tried to replace it with the .glb model, I enc ...

I am experiencing an issue where the Mongo item ID is not being successfully passed through the REST API

Recently, I've been working on developing a blog site for my class project. The main goal is to create a REST API for the blog site. I have successfully managed to display data from the database using .ejs views, except for one issue. I am facing diff ...

Adding text can only be done to the initial list item

I have a menu structured like this: <ul class="nav"> <li class="dropdown" id="123"> <ul class="nav123"> <li id="widget-products"> <ul class="123">// content populate ...

The React Route Component is responsible for managing all routes that start with "/", with the exception of the "/login" route

When accessing the /login route, the Dashboard component is also rendered. However, I need to exclude the Dashboard component while on the Login page. The exact attribute isn't suitable in this case because the Dashboard has nested paths such as /das ...

Is it possible to retrieve the IMEI number of a mobile phone using expo?

Currently working on developing a mobile app with React Native using Expo. I need to figure out a way to access the client's mobile IMEI number and display it in the front end of the app. Unsure of how to accomplish this task. Is there a method to do ...

Restricting the number of times a user can click on

I am currently displaying a table with data obtained from a database query. The structure of the table is outlined below: <table id="dt-inventory-list" class="table table-responsive"> <thead> <tr> <th>Field ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

Is it a good idea to show a loading image for slow php/mysql results?

I need some help with my website that is powered by php/MySQL for querying and displaying results. The database has grown to over 40,000 records, causing the query to slow down. I am looking for an efficient way to show a loading image while the page loads ...

Combining multiple PNG images onto a base image in PHP

I need assistance in merging 24 images with single dashes highlighted into a base circle image using PHP GD, JS or CSS. All images are in PNG format. Your help would be greatly appreciated. ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

connect the validation of forms to different components

I am currently working on components to facilitate the user addition process. Below is an example of my form component: createForm(): void { this.courseAddForm = this.formBuilder.group({ name: ['', [ Validators.required, ...

AngularJS restricts inputs to be read-only

I'm facing an issue with readonly inputs in AngularJS. I have a select element that changes the values of readonly inputs through a script. However, when I attempt to display these values using ng-model in a table as {{ng-model}}, they don't appe ...

Tips for incorporating fading text and a CTA into your content block

I am looking to protect the full content of my blog posts and allow access only to subscribed members. I want readers to see just a glimpse of the article before it disappears, prompting them to take action with a Call to Action (CTA) like in the fading te ...

Ways to resolve a 500 internal error

I have created an online test system for students, but I am facing an issue with passing answers in JSON format. Whenever I attempt to do so, I encounter a 500 internal error and I am unable to identify the root cause. Even after removing lengthy JSON dat ...

In order to achieve a sliding effect for the second div, it can be programmed to

Currently, I am working on implementing hide and show functionality in my project. However, I have come across a bug in my code that I need assistance with. When clicking on the first div element, the content opens from bottom to top instead of the desired ...

Retrieving information in Ionic

Having trouble fetching data from a server in my first ionic application. I keep getting an error that says "Cannot read Property" while trying to attach my code snippet. Here is what my code looks like: import { Component } from '@angular/core' ...

Iterating through an SVG path multiple times

If I have the arrow below and I want to place it at various locations within the svg: <svg width="400" height="400"> <path transform="translate(150,100)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" /> <path transform="translate( ...

Need to specify a parameter type for the input tag in HTML

Currently, I am developing a customized focus method for my webpage using the following script: <script type="text/javascript"> function myFunction() { document.getElementById("name").focus(); } </script> I ...

Adjust the source of the HTML5 video tag based on the orientation of an iPad

I am currently coding an HTML5 page specifically for iPad Mobile Safari, which includes a video tag for embedding video files. I have successfully implemented CSS3 media queries to determine the orientation of the iPad. My next challenge is to dynamically ...

Guide on adjusting padding for jQuery Flot graph for improved styling

I am utilizing jQuery Flot to generate a basic graph. I do not want the axes to display on either side, but this is causing the points to be slightly cut off. Any suggestions on how to resolve this issue? $.plot('#'+id, [ { data: data.values ...