Move the Div element up and down when clicked

When a tag is clicked, the corresponding div opens and closes. I would like the div to slide down and up slowly instead of appearing immediately.

<a href="" class="accordion">Click here</a>
 <div class="panel" id="AccordionDiv">
            <div class="store">
                <div class="store-row">

                    <div class="cells store-logo text-center">
                        <img src="@strStaticWebsiteUrl@(objOfferPrice.StoreImage)" alt="" />
                    </div>

                    @if (objOfferPrice.Price < objOfferPrice.UrlPrice)
                    {
                        <div class="cells text-center">
                            <div class="product-price offer-price">Rs. @String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0,0}", objOfferPrice.Price)<sup>*</sup></div>
                            <p class="real-price">Price: @objOfferPrice.UrlPrice</p>
                        </div>
                    }
                </div>
           </div>

This code snippet contains HTML followed by the associated script below:

            <script>
                var acc = document.getElementsByClassName("accordion");
                var i;
                for (i = 0; i < acc.length; i++) {
                    acc[i].addEventListener("click", function () {

                        this.classList.toggle("active");
                        var panel = this.nextElementSibling;
                        if (panel.style.display === "block") {
                            panel.style.display = "none";
                        } else {
                            panel.style.display = "block";
                        }
                    });
                        }
            </script>

Answer №1

Utilize CSS for Animated Effects

CSS animations offer a more visually appealing option compared to Javascript animations. Moreover, CSS animations can be easily halted or reversed midway through.

Javascript Example:

<script>
    var acc = document.getElementsByClassName("accordion");
    for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click", function () {
            this.classList.toggle("active");
            this.nextElementSibling.classList.toggle("slideActive");
        });
    }
</script>

CSS Styling:

.accordion {
    height: 0px;
    transition: 0.3s;
}
.accordion .slideActive{
    height: 100px;
}

(Feel free to customize the styling as needed)


You can verify if it is active by using:

this.classList.contains('slideActive');

Answer №2

If you're looking to achieve this effect, jQuery offers a method called slideToggle

To implement it, simply select the next element and use the slideToggle function:
var panel = this.nextElementSibling;
$(panel).slideToggle();

Answer №3

Absolutely! In JQuery, we have the ability to incorporate animations such as "slideDown", slideUp, and slideToggle.

$( "#ID1" ).click(function() {
  $( "#book" ).slideDown( "slow", function() {
    // This animation slowly slides down.
  });
});

The same concept can be applied with slideUp as well.

Additionally, "slideToggle" allows for both upward and downward animation effects.

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

Using React to Retrieve Array Data from an API and Implementing Filtering

I have successfully made a call to my API endpoint and passed the token. However, I only need specific details from the response data - specifically, I want to work with the first index in the array that contains fields. My goal is to fetch all the relevan ...

Python makes sure that HTML values remain constant even after a button is clicked by Selenium

I am currently utilizing Soup and Selenium to access a particular page . My objective is to extract a comprehensive list of pricing and ratings for different types of packaging available on this webpage. Displayed below is the code I have composed: impor ...

Having trouble with changing text in a link with an onclick event?

When I click on the link, I want the text to change to the second span. However, this functionality is not working. Code var reload = false; $('#change').click(function() { reload = !reload; $('#change').click(function() { ...

Show various columns in Select2

I am currently utilizing select2 and I am interested in displaying a multicolumn table as a dropdown. In order to achieve this, the width of the drop-down container should differ (be larger) than the input itself. Is it feasible to accomplish this? Furth ...

Encountering issues with multiple arguments in ajax within a C# MVC application - Further details included

There seems to be a missing piece in my code. Here's my controller method public void SubmitSweep(int personID, int DD, int MM, int YYYY, int hh, int mm, int dealId) Here's how I define my button <button id="submit@(person.Id)" clas ...

Deciphering Django Queryset JSON Data

I am looking to convert a query set into JSON data, while also ensuring that the new jQuery UI autocomplete can utilize it. The autocomplete specifically requires the keys label, id, and value in order to interpret the data correctly. Currently, my approa ...

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Utilizing angularJS to manipulate select options through objects

I am looking to populate a dropdown with category values using select options from the following object: [{ "_id": "57b4508923a10cd83c79a301", "created_by": "1", "category": "Criminal law", "__v": 0, "delete_status": "0", "active_s ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

Getting JSON with duplicate keys in JavaScript can be achieved by parsing the data using a custom function

I am attempting to retrieve JSON from a URL, but I have encountered an issue where the response object is removing duplicate keys. Is there a way to fetch the JSON without eliminating these duplicates? Below is my JavaScript code: $('document'). ...

Sending a large number of values unrestrictedly via ajax

I'm currently working on implementing a filter for the Google Maps API on our website. This filter will allow users to display information related to specific locations that they select by checking corresponding checkboxes. As I am still relatively ne ...

How can I create multiple divs that look alike?

I've taken on the challenge of developing our own interpretation of Conway's "Game of Life" for a project. To represent my 20x20 grid, I decided to create nested divs - the whole grid is one div, each row is a div, and every cell within that is a ...

Tips for creating a flexible popover widget

I am facing an issue with my project that has a popover (ng-bootstrap) similar to what I need. The problem is that the tooltips and popovers are not flexible when it comes to resizing the page. To address this, I attempted to put a mat-grid (which works pe ...

Unusual performance issues observed in a flexbox when adjusting window size in mobile Chrome

Encountering an unusual issue with flexbox on a mobile browser. For a visual demonstration, view this gif Specifically happening on Chrome mobile on a Google Pixel phone. Using a resize script to adjust element sizes due to limitations with 100vh: windo ...

Utilizing jQueryUI for rendering tabbed content with JSON data

Although I have the ability to load JSON data that is returned (appearing "as is" in my HTML page), I am facing an issue where the raw JSON data does not disappear. The code I have used is as follows: $( "#tavole" ).tabs({ cache : false, event: "m ...

Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_A ...

What is the best way to contain several elements in a flexbox with a border that doesn't span the entire width of the page?

Just dipping my toes in the waters of web development and I've come across a challenge. I'm attempting to create a flexbox container for multiple elements with a border that doesn't stretch across the entire width of the page, but instead en ...

Executing a curl POST request within an npm script

I recently added a new script to my npm scripts in the package.json file, but I'm running into issues due to the single and double quotes. The problem seems to be with the internal double quotes within the payload. "slack": "curl -X POST --data-urlen ...

Keep track of the progress of a PHP function and show it using AJAX

I am exploring ways to display the progress of a PHP function in my web browser. While one option is to store the progress in a database and continuously poll for updates while waiting for a response with AJAX, I am curious if there is a more efficient met ...