Utilize CSS transitions to animate the display and concealment of a div element

I have a piece of code below where I am toggling the visibility of a div with the id "popdiv" when a button is clicked. I would like to incorporate a transition effect into this toggle action. Currently, the div simply appears and disappears abruptly without any smooth transition. I have tried adding various transition and animation effects but none seem to be working.

$('#pop').click(function(){

    $('#popdiv').toggle();

})
#popdiv{
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background-color: aqua; width: 50%; height: 20%;" >
    <button id="pop">CLICK</button>
</div>
<div style="background-color: cadetblue; width: 30%; height: 40%;" id="popdiv">
        POPUP
</div>

Is there a way to achieve the desired transition effect?

Your help is greatly appreciated!

Answer №1

To accomplish this, one can use the slideToggle() function in jQuery by implementing the following code:

$("#pop").click(function(){ $("#popdiv").slideToggle(1000);

});

Answer №2

It's best to avoid using the toggle() function as it limits control over transitions.

Instead, consider combining JavaScript and CSS for more flexibility. The display property lacks animation capabilities, making it unsuitable for creating transitions.

Opt for utilizing a mix of the opacity, visibility, and transition properties in your CSS. Start with setting opacity to 0, visibility to hidden, and applying transitions on these attributes by default.

Create a CSS class where opacity is set to 1 and visibility to visible. This class represents the visible state of your element.

Next, use JavaScript—perhaps jQuery—to toggle this class on the desired element for showing or hiding content. You can achieve this using the toggleClass() method.

$('#pop').click(function(){

    $('#popdiv').toggleClass('show');

})
#popdiv {
  opacity: 0;
  visibility: hidden;
  transition: 500ms ease-in-out;
  transition-property: opacity, visibility;
}

#popdiv.show {
  opacity: 1;
  visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background-color: aqua; width: 50%; height: 20%;" >
    <button id="pop">CLICK</button>
</div>
<div style="background-color: cadetblue; width: 30%; height: 40%;" id="popdiv">
        POPUP
</div>

Answer №3

If you want to incorporate animations, consider using the .animate method in your code.

Here is a helpful resource that elaborates on this topic: https://www.w3schools.com/jquery/jquery_animate.asp

To enhance your code, I eliminated any external CSS dependencies, updated the jQuery version, and introduced the use of display: none for your popup container.

$('#pop').click(function(){
    $('#popdiv').animate({
        width: 'toggle'
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background-color: aqua; width: 50%; height: 20%;" >
    <button id="pop">CLICK</button>
</div>
<div style="background-color: cadetblue; width: 30%; height: 40%; display: none;" id="popdiv">
        POPUP
</div>

Answer №4

alternative choices: you have the option to adjust the fadeIn duration and the transition speed of .5s.

$('#pop').click(function(){
    $('#popdiv').fadeIn(1000); 
})

$('#pop2').click(function(){
   $('#popdiv2').toggleClass('showHide');
})
#popdiv{
   display:none;
}

#popdiv2 {
  opacity: 0;
  transition: all .5s ease-in-out;
}
#popdiv2.showHide {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background-color: aqua; width: 50%; height: 20%;" >
        <button id="pop">CLICK</button>
    </div>
    <div style="background-color: cadetblue; width: 30%; height: 40%;" id="popdiv">
        POPUP
    </div>
<br><br><br>
<div style="background-color: aqua; width: 50%; height: 20%;" >
        <button id="pop2">CLICK TWO</button>
    </div>
    <div style="background-color: cadetblue; width: 30%; height: 40%;" id="popdiv2">
        POPUP TWO
    </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

How can you generate an HTML table row without using the <tr>

Greetings everyone! I am currently working on creating a table using HTML, Bootstrap 5, and CSS to display various article details. Each article may have one or multiple variants, and I would like these variants to be displayed as rows within the parent ar ...

Controlling MYSQL data is not possible

When I retrieve data from the database, everything is functioning correctly, but the data flow seems uncontrolled. Here is a snippet of my code... <?php session_start(); include 'conn.php'; include '../includes/layouts/header.php'; ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

Is it possible to incorporate an element using absolute positioning using jQuery or Javascript?

When trying to add a new element on the screen, I am facing an issue with the absolute positioning not working properly. Sample Code in Javascript function drawElement(e,name){ $("#canvas").append("<div id='" + name + "' class='e ...

Issue with displaying random 1px background image on Chrome browser

I'm facing an issue with the background image not appearing for one of the links in my navbar in Chrome. Specifically, the image doesn't show up between the "Athletics" and "Bowling" links. Interestingly, the background image displays fine in Fi ...

Utilizing the null value within a function

While learning from an online tutorial, I came across a situation where the predefined value of the function was set as null for data and details. I'm curious about the significance of using null here. Can you clarify what it means? onClick={(data, d ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

How can I retrieve the current quarter, as well as the three preceding quarters, including the corresponding year, using Moment.js

Could you provide a method for retrieving the current quarter and the previous three quarters in conjunction with the year? For instance, it should output four quarters as follows: q3-2016 q2-2016 q1-2016 q4-2015 ...

I am interested in integrating an Excel file into my ASP.NET MVC application that includes mathematical equations and images

I am looking to upload an Excel file into my ASP.NET MVC application, which includes mathematical equations and images. Can anyone guide me on how to achieve this? The application is designed as an online exam system for students preparing for entrance e ...

The mouse scroll function is not functioning properly with the mCustomScrollbar jQuery plugin

I've been troubleshooting a problem without success, so I decided to download the jQuery plugin mCustomScrollbar. Everything seems to be working fine except for one thing - I can't scroll using the mousewheel on my test page. The console is clear ...

Making a CSS table fit perfectly inside a container

After reading numerous recommendations on the subject, none of them seem to be effective in my particular situation. The issue lies with a table that is nested within a container ('div' element) as shown below: <div class="container"> ...

PHP not displaying value upon submission

Looking for a simple PHP code to post a value and echo it inside an if(isset()) statement when clicking on the submit button, but unfortunately, it's not functioning as expected. <?php if(isset($_GET['q'])) { $q=$_GET[&ap ...

Attempting to set up an Ajax webform with various outputs, but encountering issues with functionality

I'm encountering an issue while creating interactive exercises. I want to display correct or incorrect answers immediately after submission using JSON for retrieving responses, as suggested in a forum. However, my AJAX code isn't working at all. ...

Create a project using Next.js and integrate it with the tailwindcss framework

My application utilizes TailwindCSS and NextJs. I am facing an issue where certain classes are not working after running npm run start, following a successful run of npm run dev. For example, the classes h-20 / text-white are not functioning as expected, w ...

Tips for reducing the height of the footer without compromising the alignment of the text within

My attempt to reduce the height of my footer in CSS using padding, margin, and other methods was unsuccessful. All of these adjustments either pushed the footer completely out of the bottom or left the text uncentered. footer { background: #fce138; wid ...

Is there a way to automatically activate the "Add" button when I hit the enter key in the text box?

Being someone who relies on to-do lists, I implemented a system where you can input tasks into a textbox and click the add button to see them listed below. However, I found it cumbersome to keep clicking the add button every time I wanted to quickly add mu ...

React Redux is facing difficulties resolving its own modules

Upon running webpack for my project, an error regarding the React-Redux package not being able to resolve some of its internal modules has been encountered: ERROR in ./node_modules/react-redux/es/index.js Module not found: Error: Can't resolve ' ...

How can I access a component variable within the styles in Angular?

Is it possible to utilize a variable width in my Angular 5 component template? I would like to achieve something similar to this: <style> input:checked + .slider:before { transform: translateX({{width}}px); } </style> The &apo ...

Using JSON response directly in loaded HTML in Angular 2 is a straightforward process. Follow these steps to

As I delve into Angular 2 and explore its components, one question that arises is how to display data received from a server in JSON format on an HTML page. In Angular 1.x, we could directly assign a JSON object to a variable and use it in HTML using the & ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...