Issues with CSS transitions not functioning properly following the use of toggleClass()

I recently implemented a toggle-menu feature, which you can see in action on this demo.

To enhance the toggle-menu, I added a CSS transition effect to div.nav-menu, utilizing max-height:0; and increasing it to max-height:480px;.

However, after clicking the menu toggle to reveal the menu, the transition works perfectly. Yet, upon clicking the toggle to hide the menu again, the transition fails to work.

I'm puzzled as to what might be causing this issue. Any insight would be greatly appreciated!

Answer №1

Your understanding of CSS Transitions is incorrect. Contrary to your belief, they do not trigger animation when classes are added or removed; rather, the animation occurs only when CSS properties are changed. It seems that you are directly adding and removing classes in this scenario.

Allow me to present a solution:

$( '.menu-toggle' ).on( 'click', function() {
    if(nav.hasClass('toggled-on')) {
       menu.css('maxHeight', 0);
       //^ By modifying 'max-height' first, the Transition animation will be activated
    }
    else menu.css('maxHeight', '480px'); 
         // ^ Alternatively, setting it back to 480px if needed;
} );

// Then, I attach an event listener for the end of the transition on the element to toggle its class
// Once the transition completes

menu.on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function() {
    nav.toggleClass( 'toggled-on' );
});

View Updated Fiddle

Answer №2

If you're looking to achieve the desired effect, there's a simpler method available.

View Demo

JavaScript

$(function() {
    $('.menu-toggle').click(function(){
        if($('.nav-menu').is(':hidden')){ // check if menu is hidden
            $('.nav-menu').slideDown();}  // slide down if hidden
        else{$('.nav-menu').slideUp();}   // slide up if visible
    });
});

CSS

html {
    font-size: 100%;
    overflow-y: scroll;
}
body {
    max-width: 860px;
    margin: 0 auto;
    font-family: Arial, sans-serif;
}
.main-navigation {
    clear: both;
    min-height: 50px;
    margin-top: 25px;
    position: relative;
}
.menu-toggle {
    cursor: pointer;
    display: inline-block;
    font: bold 15px/1.3;
    margin: 0;
    padding: 10px;
    color: #fff;
    background-color: #333;
}

.nav-menu {
    margin: 0;
    background-color: #333;
    display: none;
    overflow: hidden;
}

.nav-menu ul {
    display: block;
    margin: 0;
    padding: 0;
    width: 100%;
}
.nav-menu li {
    display: block;
    padding: 10px;
}
.nav-menu li a {
    display: block;
    padding:10px;color:#fff;line-height:1;
    text-decoration: none;
}
.nav-menu li a:hover,.nav-menu li a:focus{background:#444;}
.toggled-on li a:active{background:#2A8A15;}

jQuery .slideUp() Documentation and jQuery .slideDown() Documentation

Answer №3

It's recommended to use height instead of max-height

.nav-menu {
    margin: 0;
    background-color: #1e1e1e;
    height:0;
    display: block;
    clear: both;
    overflow: hidden;
    -moz-transition:all 350ms cubic-bezier(.42,0,.58,1);
    -ms-transition:all 350ms cubic-bezier(.42,0,.58,1);
    -o-transition:all 350ms cubic-bezier(.42,0,.58,1);
    -webkit-transition:all 350ms cubic-bezier(.42,0,.58,1);
    transition:all 350ms cubic-bezier(.42,0,.58,1);
}
.toggled-on .nav-menu {
    display: block;
    height:480px;
}

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

Creating a scrollable table body in Bootstrap 4

I am struggling to make a large table mobile-friendly using Bootstrap 4. The table can have up to 10 columns and 100 rows. I need a CSS solution that achieves the following: A fixed header with each column having the same width as its respective row An x/ ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

Change in navigation bar appearance on scroll down

I am attempting to create a fixed navigation bar by customizing the Bootstrap CSS file. The goal is to change the navbar's color and make it stick to the top when scrolling down. Although I followed the instructions in this article, the JS code I add ...

The Jquery code for Fullpage.js is causing unexpected behavior on the HTML page

While following a tutorial at the given link, I encountered an issue. Around the 9:08 mark, the instructor adds some JavaScript and demonstrates that fullpage.js is working. However, when I refresh the page after implementing the new code, it doesn't ...

Utilizing jQuery to load HTML content into a div restricts my ability to navigate back and forth seamlessly

I am new to jquery and currently working on my first project. In my index.php file, I have included: header.html indexview.html footer.html. The indexview.html file consists of two divs - one for the menu on the left and another (div id="content") f ...

The issue with Go Code is that it fails to display the JSON data received from a jQuery

Problem Description The issue I am facing is that Go Code is not displaying the posted JSON value from jQuery AJAX. Main Go Code routing := chi.NewRouter() routing.Post("/authenticate", AuthenticateRouter) Go Code Snippet func AuthenticateRouter(w http. ...

Is there a way to arrange my bootstrap navigation tabs vertically on my mobile device?

I have a group of five bootstrap navigation tabs that are evenly spaced and visually appealing on desktop screens. However, when viewed on a mobile device, the text within the tabs becomes cramped together. How can I make the tabs stack vertically on mobil ...

Ways to manipulate external CSS classes with styled components without direct access

Currently, I am utilizing react-table and wanting to implement CSS rules for the class rt-td, which is not accessible or adjustable through their API functionalities. In traditional CSS practice, I could easily override the CSS class within my stylesheet. ...

jQuery experiences compatibility issues with IE7, IE8, and IE9 while functioning smoothly on other web browsers

An issue has been encountered with this query in IE7, prompting an error message stating "Object Expected". While in IE8/9 there is no error but the query does not function properly. However, it works fine in all other modern browsers. If (jQuery("#tabs ...

Identifying various device platforms through CSS styling

After extensive research and testing, I have explored a variety of resources and solutions for implementing device-specific CSS on my webpage. Here are some of the references I've studied: Detect iPhone/iPad purely by css Detect Xoom browser (Andro ...

It appears that using Jquery's .on function in combination with AJAX is not functioning as expected

What is the reason why this code snippet below doesn't work as intended? $(function() { $('#settings').on('click', '.link', function(e) { e.preventDefault(); alert('okay'); }); }); ...

Tips for altering the design of a registration page

I'm struggling to modify my registration page layout so that the avatar is positioned on the left while the username, password input boxes are on the right. I attempted to use split divs without success and also tried adjusting the positioning of the ...

Scrolling effect on Bootstrap tabs activated when clicked

I'm currently utilizing Bootstrap 3 Tabs in the following manner: <ul class="nav nav-pills nav-justified"> <li><a href="#tab-1t" data-toggle="tab"></a></li> <li class="active"><a href="#tab-2" data-toggle= ...

Tips for keeping the DropDown Menu displayed even after moving the cursor away from the targeted element in Material-UI

import React from 'react'; import { makeStyles, Typography, Grid } from '@material-ui/core'; const styles = makeStyles((theme) => ({ root: {}, textStyle: { fontFamily: 'brandon-grotesque-black', tex ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

When a div is clicked, the Checkbox ("checked",true) is selected, however, the $checkbox.change(function()... does not account for this

In my current scenario, there is a table containing records along with a set of buttons for actions such as add, edit, and delete. In addition to this, each record has a checkbox at the beginning, which allows for multiple selection (for deletion purposes) ...

Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/ In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top. I have explored various solutions for thi ...

Issue with validating file upload size in Internet Explorer (IE) is yet to

Hello, I have successfully implemented upload max file size validation using jQuery. It seems to be working perfectly in Chrome and Firefox, but unfortunately not in IE. $('#file').change(function() { fileSizeError = (this.fi ...

Delaying the appearance of an element using jQuery before hiding it

Can someone help me troubleshoot why the code below isn't functioning properly? I'm trying to click an element, hide it for a moment, and then show it again. http://jsfiddle.net/ba8bJ/ $('#myButton').click(function() {$(this).hide().de ...

Tips for integrating DataTables selection filtering functionality

Here's a snapshot of my screen I'm attempting to utilize data tables This is what I have on the main page $('#student-listing-table').dataTable(); $('#student-listing-table').find('label').html('Search By Nam ...