Altering the interaction of a dropdown element within a banner to transition seamlessly

I am attempting to create a dropdown and rise-up banner without relying on jQuery. My goal is for it to smoothly descend and rise when the triangle is pressed, as shown in the image. Currently, the triangle is styled as text (though it could also be a button).

The issue at hand is how to alter the behavior of an element (triangle) after it has been clicked multiple times. Upon the first click, the banner should drop down and then the triangle needs to change direction to point upwards, while 'Show' becomes 'Hide'. Subsequent clicks should cause the banner to rise up again, with the triangle pointing downwards.

For clarity, here is an image: https://i.sstatic.net/XYW5m.png

Following advice from muka.gergely, I have simplified the example for myself:

HTML:

<div class="dropdown-wrapper">
        <div class="btn-dropdown">
            Show ▼ 
            <div class="dropdown-content-container">
                <!--Banner-->
            </div>
        </div>
</div>

JavaScript:

<script>
        const btns = document.querySelectorAll('.btn-dropdown')

        btns.forEach(btn => {
            btn.addEventListener('click', function(e) {
                /* Changing the name of the 'Banner' is not working */
                /* const initialText = "Banner"
                /*if (btn.textContent.toLowerCase().includes(initialText.toLowerCase())) {
                    btn.textContent = 'Hide a Banner';
                } else {
                    btn.textContent = initialText;
                }  
                */
                e.target.classList.toggle('open');
               
            });
        })
</script>

CSS:

.btn-dropdown {
    position: relative;
    cursor: pointer;
    padding: 8px 16px;
    border: 1px solid gray;
}
 
.dropdown-content-container {
    overflow-y: hidden;
    max-height: 0;
    transition: all 1.50s;
}
 
.btn-dropdown.open>.dropdown-content-container {
    height: 500px;
    max-height: 500px;
    transition: all 1.50s;
}

jsfiddle

Answer №1

If you're facing a challenge with the smooth transition in your design, consider making a simple adjustment by replacing the max-height properties with just the height property.

The unnecessary use of max-height can interfere with the css transition effect.

Also, there may be no need for the second transition property if it's already defined elsewhere in the code.

.dropdown-content-container {
  overflow-y: hidden;
  height: 0;
  transition: all 1.50s;
}

.btn-dropdown.open>.dropdown-content-container {
  height: 500px;
}

To address the issue of changing the name, ensure that the text you wish to modify is enclosed within an element for direct access without affecting the entire structure (including the container).

Start by modifying the HTML code accordingly (you can use any appropriate element like span)

<div class="btn-dropdown">
    <span class="dropdown-content-label">Show ▼</span>
    <div class="dropdown-content-container">
        <!--Banner-->
    </div>
</div>

Then, adjust the JS code slightly to align with this HTML change by targeting the label specifically, rather than the entire dropdown component.

const btns = document.querySelectorAll('.btn-dropdown')

btns.forEach(btn => {
    btn.addEventListener('click', function(e) {
        const initialText = "Show ▼"
        const label = btn.querySelector(".dropdown-content-label");
        if (label.textContent.toLowerCase() === initialText.toLowerCase()) {
            label.textContent = 'Hide ▲';
        } else {
            label.textContent = initialText;
        }  
        btn.classList.toggle('open');
    });
})

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

Retrieving values from nested json response with dynamically changing response names

When utilizing nodejs to send a get request to the vultr api, I receive a nested json response upon parsing it: Please note that the values '36539496' (and also '36539499') are dynamically generated SUBIDs unique to each server. Unfort ...

Tips for inserting a personalized image or icon into the ANTD Design menu

Can anyone help me figure out how to replace the default icons with a custom image or icon in this example: https://ant.design/components/layout/#components-layout-demo-side I attempted to do it by including the following code: <Menu.Item to="/" key=" ...

Is there a way to use JavaScript or jQuery to automatically convert HTML/CSS files into PDF documents?

While using OS X, I noticed that in Chrome I have the option to Save as PDF in the print window by setting the destination to "Save as PDF". Is this feature available on Windows? Is there a way to easily save to PDF with just one click? How can I access t ...

Tips on customizing the appearance of JFoenix components within JavaFX Scene Builder using CSS

I'm struggling to customize the appearance of a JFXButton using CSS stylesheets. While some properties are working fine, such as background color and size, I can't seem to get font color and weight to apply: .eliminarBtn { -fx-background-col ...

HTML5 Embedding a redirect iframe for connection status validation [UPDATE]

I've created an offline HTML file and embedded an iframe within it that redirects to a site if there is an available internet connection. However, in the event of no internet connection, the iframe will redirect to an offline page. Could someone plea ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

Building an anchor tag that employs the HTTP DELETE method within an Express.js app

Recently, I delved into using express.js with handlebars.js as my template engine. One task I wanted to tackle was creating a delete link that followed RESTful principles and used the HTTP DELETE verb instead of GET. After some trial and error, I discover ...

Separating MS Edge Driver into its own configuration file in wdio

Seeking assistance with creating separate configuration files for Chrome, Firefox, and Microsoft Edge drivers on webdriver.io (version 7.19.3). Struggling to configure the Microsoft Edge driver on a Windows 10 machine while maintaining the main wdio.conf.j ...

Using AngularJS to implement conditional ng-class with multiple matches for a single option

I encountered an issue with the following code snippet: <span class="label" ng-class="{ 'label-success': resp.level == 'A1', 'label-success': resp.level == 'A2', ...

Reversed Sink CSS3 Animation moving to the left side

Currently, I am working on creating an animation that gives the illusion of a div sinking backward and then being pushed to the left once it has finished falling back. Although I am using CSS3 for this project, I am not very familiar with the animation pr ...

A guide on setting background images with the img tag

I have created a PHP method that generates an HTML IMG tag. For example, ImageClass::getImage('sample.png' , 'myTitle') will output the string <img src="sample.png" title="myTitle" /> In my CSS file, I have used the following cod ...

Immediately executing $digest following $watch's declaration results in an error message stating "$apply is currently in progress

I am new to Angular and I'm trying to figure out why I'm getting the error "$apply is already in progress..." with the following code snippet. Here is the code, which closely resembles what's in the Angular documentation: https://docs.angul ...

"Can you explain the concept of an undefined id in an AJAX request

Within my mongodb database, I have two Tables: GstState Store While working on my Store form, I encountered an issue where the JSON response was returning an undefined id when trying to select a state based on country via an ajax call to fetch GstStates ...

What is the best way to trigger a 'Save As' dialog box on a browser when a button is activated within an Angular application, guaranteeing cross-browser compatibility?

The solution needs to be compatible with both Windows and Mac operating systems. Additionally, we should be able to specify a default file name and type. ...

A guide on building a scroll-friendly content area using flexbox

For my layout, I wanted a design with a header and footer that remained fixed at the top and bottom of the window, and content in between. That part was relatively simple to achieve. However, I also needed the main content area to have its own header and ...

Expand the list in both vertical and horizontal directions

I have a unique way I want this list to function: When clicked, it should reveal a vertical list. If an item in the vertical list is clicked, it should display horizontally with more information about that item. All items should be hidden until either Te ...

Can a submit button be created that integrates both a radio button and submission functionality?

Is there a way to combine a radio button and submit button into one element for submitting the value just with a click? Currently, I have a radio button and a separate submit button in my code, but I want to streamline it. This is the current code snippet ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

React-select fails to trigger form submission when the Enter key is pressed

Currently, I am utilizing Formik and React-Select in my project, and I'm hoping to enable the form submission by pressing enter while focused on a select input. Interestingly, when I'm focused on any other input field and press Enter, the form s ...