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

Cross-browser compatibility issues with Ajax functionality observed on a single device

After successfully using a CMS system I built with jQuery and PHP for over a year, I encountered a strange issue while presenting it to a potential customer. Despite working flawlessly for multiple users on various platforms up until that point, the custom ...

Parcel Bundler works perfectly fine on localhost, however, an error is being displayed on the index.html file in the Dist folder

Currently, I am in the process of learning how to use Parcel for bundling purposes. I have set up a index.html file that is connected with index.js. Surprisingly, everything works perfectly fine when I access it via localhost:1234 using Parcel. However, wh ...

Do you have to host a node server to run Angular applications?

(say) I am currently working on a project that utilizes Laravel or PHP for the back-end and Angular for the front-end. In my setup, I am using angular.js files from a CDN, which should work fine. However, I find myself confused when tutorials and books me ...

I would like to hide the button if there are fewer than five visible

When there are less than 5 visible buttons, I want the button to be invisible. The state visible outputs 5 buttons each time. On the detail page, I would like to have the buttons invisible if there are fewer than 5 outputs. In my current code, when ther ...

Tips on attaching a class to elements in a loop when a click event occurs

In my HTML, I am displaying information boxes from an array of objects that are selectable. To achieve this, I bind a class on the click event. However, since I am retrieving the elements through a v-for loop, when I select one box, the class gets bound to ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

I am encountering an issue where I am unable to send a HashMap String to a PHP server, and I am not receiving a JSONArray in the

How can I send a hashmap string to a PHP server without receiving back a JsonArray using Volley in Android? CM =$_POST['code_send']; $db =Db::getInstance(); $records = $db->query ("SELECT * FROM p_users WHERE c_meli='$CM'"); $js ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Bidirectional communication between two AngularJS scopes or controllers utilizing a service

I am facing numerous situations where I require clicks or other interactions to trigger actions in a different area of the webpage (one-way communication). Now, I have encountered a need for bidirectional communication, where changes made in element A can ...

I am looking to modify the anchor link and image source using JQuery based on the specific div ID

Looking to update the link of an anchor and source of an image inside this div when clicking on the FR button. I need help figuring out how to do this with JQuery. Here's the code: <div id="my_id"> <a href="wwww.google.com&qu ...

disable event listeners on the DOM

I am currently developing a web framework and focusing on integrating XSS prevention measures. I have successfully implemented data escaping for database storage, but now I am faced with the challenge of allowing users to save generated HTML without riskin ...

The beta version of Angular 2.0 introduces the BrowserDomAdapter for easy access to the DOM

I have a Component in Angular 2.0 that is attempting to utilize the DOM Adapter API from Angular's BrowserDomAdapter documentation. The initialization of this DomAdapter can be found here. However, I am uncertain about whether the Dom Adapter needs t ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

Updating Hiddenfield Value Issue in Jquery

Having an issue with Jquery: <input type="hidden" id="is_subpage" value="FALSE" /> <input type="hidden" id="is_page" value="TRUE"/> <input type="hidden" id="page_id" value="0"/> <input type="hidden" id="page_domain" value="{tic}" /&g ...

Using the jQuery before() method to manipulate form fields

Is it possible to utilize the jQuery before method to insert a form? An example scenario could be as shown below: <script> $(document).ready(function() { $("button").click(function() { $("button").before('<form><input type="text ...

Error message encountered: "myData undefined while executing server in Node.js"

const express = require('express'); const app = express(); app.post('/', (req, res) => { let newData = new contact(req.body); newData.save() .then(() => { res.send("Data has been successfully saved to ...

Utilizing ng-repeat to loop through a div element that consists of various nested tags

I need to display multiple tabs, with each tab having a table where the values are populated from a database. The number of tabs is dynamic and fetched from another page of the application. All tables have the same structure but different values. How can I ...

Guide for extracting the first matching group with regex in node.js

Extracting a specific value from a string in a text file can be tricky. In the example below, the goal is to get the value of valuetext: <CONFIG_entry name="Konfiguration:Allgemeine Einstellungen:CMS-Server:Port" valuetext="15000" value="15000" adr="CL ...