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

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...

Dragging the world map in D3 causes it to appear jumpy and erratic

I'm currently working on a Vue project to create an interactive world map that allows users to drag and zoom. I've attempted to integrate D3 for this purpose, but encountered an issue where the map jumps to the bottom right of the page whenever I ...

Struggling to make the CSS :not() selector function correctly as needed

I've been struggling to make the CSS :not() selector work in a specific way and despite searching for solutions, I haven't been successful. I came across some helpful resources like this page, but I couldn't figure it out on my own. Hopefull ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

Is Apache required for running NodeJs?

Recently, I set up a web project on my local machine following a tutorial. With the help of XAMPP, I was able to install MySQL and Apache to run my Node.JS backend. Now, I'm looking into hosting the project on an external server to make it accessible ...

Tips on incorporating background color into HTML emails dispatched via PHP mail()

Struggling to add a background color to my HTML email. I've attempted various methods: Inserting <script> tags with CSS code inside Adding bgcolor in body tags Using a CSS style sheet All to no avail. I suspect it could be the email provi ...

retrieving data from GET variables and sending to a PHP array

Is there a way to retrieve form variables and store them in an array in memory without reloading the page? I'm not very experienced with this, so any guidance would be appreciated. My goal is to update a JSON file using PHP based on form inputs. JSON ...

ApEditingError: The method editAp is not defined in _this.props

I am facing an issue while trying to invoke the function editAp located in the func.js file from Edit1.js. I have provided the code snippets below for better understanding: import firebase from "firebase"; if (!firebase.apps.length) { firebase.initializ ...

How can I position text next to an input within a <td> element in a vertical arrangement?

Below is the HTML code: <fieldset><legend>Callout Report</legend> <table> <tr><td>Start Time</td><td> <input type="text" id="startTimeUI" autocomplete="off" /> </td></tr> <tr><td& ...

Tips for deploying a Nuxt application using an alternative command line interface

Despite my best efforts scouring the internet for a solution, I have yet to find a method to resolve my issue. The problem lies with my nuxt.js SPA being blocked by my company firewall when accessed by other users at the designated host/port. While servin ...

Customizing MaterialUI styles in React: A step-by-step guide

When utilizing Material UI with React, I am facing difficulty styling the Outline Select component according to my preferences. How can I override the default styles effectively? Even after using withStyles, I am unable to achieve the desired appearance a ...

Containers do not line up properly with each other. Adjusting the width leads to unexpected consequences

As someone who is new to HTML and CSS, I am facing a challenge with aligning the items within a navigation bar on my website. The list serves as a navigation bar and is contained inside the "inner header" div. While I was able to align the entire "nav" con ...

Sort Messages By Date Created

While using Vue, I encountered a general JavaScript question. I am fetching cat messages from an API for a chat interface. The initial call returns an array of objects where each object represents a chat message: data: [ {id: 1, created_at: "2022-05 ...

Create another div for the remaining vertical space occupied by the sibling div?

I currently have 3 different divs nested within each other: <div class="a"> <div class="b"> </div> <div class="c"> </div> </div> Here is the current CSS styling applied to these divs: .a { hei ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

Modifying the file name during the download process using AngularJS

Looking for a solution to download a file from an ajax GET request in angularjs? Currently, I am using an invisible iframe to trigger the "Save as" popup for the downloaded file. However, I need to change the name of the file before the popup appears. If ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

Say goodbye to <!DOCTYPE html> when using htmlAgilityPack

I'm currently developing an app for WP 8.1, and one of the tasks I need to accomplish is parsing a webpage with the following structure: <!DOCTYPE html> <html> <body> <table cellspacing="0" cellpadding="0" border="0" style="b ...

Add the AJAX response to a div element when the submit button is pressed

Working on a WordPress project involving an AJAX call, I need to return the result of a row to a div with the ID #hero. The challenge is that since the result is inside a for loop and each row has its own hero div, I want the result to be returned to the c ...

Cache AJAX submission on IE8

In my current project, I have implemented a function for uploading and displaying images. The main purpose of this function is to avoid reloading the entire page when uploading and previewing images using AJAX. After uploading an image, it is displayed in ...