Submenu animation that "bursts onto the scene"

I'm facing an issue with my menu that has sub-items inside it. To achieve the animation effect I desire, I need to extract the width, height, and first-child's height of the sub-menu. While my animation is working most times, there are instances when the sub-menu just "pops up" without animating its width.

You can see The Fiddle showcasing the problem.


This is the code I am using:

var j = jQuery.noConflict();
j(document).ready(function () {

    j('ul.nav').removeClass('nav').addClass('jnav'); //Add jquery Class to our menu 

    j('ul.jnav li').hover(function () {
        if (j(this).children('ul:first').hasClass('jsub-menu')) { //Check for "jsub-menu" Class
            return false; 
        } else { 
            j(this).find('ul.sub-menu:first').not(':animated').slideDown(500);
        }

    }, function () {
        j(this).find('ul:first').slideUp(500, function () {
            j(this).removeClass('jsub-menu').addClass('sub-menu');
            j(this).css({
                'height': '',
                'width': ''
            });
        });

    });

    j('ul.jnav ul.sub-menu a').hover(function () {
        j(this).addClass('active');

        if (j('.active').next('ul.sub-menu').length) { 
            j('.active').next('ul.sub-menu').css({
                'visibility': 'hidden',
                'opacity': '0',
                'display': 'block'
            }); 

            var get_width = j('.active').next('ul.sub-menu').outerWidth(true); 
            var get_height_of_first_child = j('.active').next('ul.sub-menu').children('li:first').outerHeight(true); 
            var get_submenu_height = j('.active').next('ul.sub-menu').outerHeight(true);

            j('.active').next('ul').removeClass('sub-menu')
            .addClass('jsub-menu').css({
                'visibility': '',
                'opacity': '',
                'height': get_height_of_first_child + 'px',
                'width': '0'
            });
            j('.active').next('.jsub-menu').animate({
                width: get_width
            }, 1000, function () { 

                j('.active').next('.jsub-menu').animate({
                    height: get_submenu_height
                }, 1000); 
            });
        }
    }, function () {
        j('.active').removeClass('active');
    });

});

I suspect that the conflict between my Slide Up/Down animations and animate width/height functions might be causing this issue, despite trying different combinations of stop() methods. I've been struggling with this for days now, so any help or insights from you would be greatly appreciated.
Thank you!!

Answer №1

After much effort, I successfully reproduced the error.

To address the issue with the animation, I have crafted this code as a replacement for your current one.

var animating = false;
function animate($elm, options, callback) {        
    if (animating) 
        return;

    animating = true;
    $elm.animate(options, 1000, function() {
        animating = false;

        if (callback != undefined)
            callback();
    });        
}

You can invoke it like this within your hover callback.

animate(j('.active').next('.jsub-menu'), 
        {
            'width': get_width,
            'height' : get_submenu_height
        });

This code ensures that another animation is not triggered while one is already in progress. The flag is set to false once the animation finishes, allowing other animations to take place.

If needed, you can include a callback function to execute after the animation completes, but since you are adjusting both height and width simultaneously, it may not be necessary in your case.

Upon testing for approximately a minute, the animation appeared quite smooth.

For the updated version, you can refer to this revised feedle: http://jsfiddle.net/gabrielcatalin/TNxJ4/1/

P.S. It might be advisable to utilize the $ symbol instead of 'j' when dealing with jQuery wrappers.

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

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...

Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error: TypeError: firebase.auth(...).currentUser is null This is the content of my index.js ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...

What is the best way to retrieve a specific object from a JSON file using a Get request in a Node.js application?

My focus is on optimizing an API, which is why I'm working with only the data that's essential for my analysis. I've set up a route to extract specific objects, but I'm only interested in four of them: account_manager, fronter, closer, ...

styling a flex container with aligned text and buttons

I'm attempting to align text on the left and button controls on the right within a display: flex div. <CustomFieldContainer> <StyledWellContainer> <FieldDetails key={id}> <H4 bold>{label}</H4> <Styled ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

The process of toggling a div to slide up and down explained

I'm attempting to create a slide toggle effect on a hidden DIV when a user hovers over specific link buttons. JavaScript: $(function () { // DOM ready shorthand var $content = $(".sliderText"); var $contentdiv = $(".sliderCo ...

I'm working on a CSS project and my goal is to ensure that all the items are perfectly aligned in a

I have been working on a ReactJS code and I'm struggling to achieve the desired result. Specifically, I am using Material UI tabs and I want them to be aligned in line with an icon. The goal is to have the tabs and the ArrowBackIcon in perfect alignme ...

Introducing a pause in the function while rendering objects

After inserting setInterval into the code, it is causing all lasers to be delayed by one second. I am looking to have them fired in this order: - initially fire laser1 and laser2. - then take a 1-second break before firing another set of lasers, a ...

Utilizing Python's urllib and urllib2 to automatically populate web forms

My goal is to automatically submit an HTML form using both urllib2 and urllib. import urllib import urllib2 url = 'site.com/registration.php' values = {'password' : 'password', 'username': 'username& ...

Utilize jQuery and JavaScript dynamically in an HTML document on iOS devices

Having some trouble with this code snippet and getting it to work as intended. - (void)viewDidLoad { [super viewDidLoad]; _webview.delegate = self; [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBun ...

What could be causing the Or operator to malfunction within the ng-pattern attribute in AngularJS?

Currently, I am implementing the ng-pattern="/^(([A-Za-z]{0,5}) | ([0-9]{0,10}))$/". However, it seems like the input control is not accepting values such as "asd" or "09", despite my expectation that both should be valid inputs. Do you think the pipe sy ...

Give properties to a function that is being spread inside an object

While working with React, I am facing a challenge of passing props from the instanced component into the mockFn function. The code example below is extracted and incorporates Material UI, but I am struggling on how to structure it in order to have access t ...

Arranging unrelated divs in alignment

http://codepen.io/anon/pen/Gxbfu <-- Here is the specific portion of the website that needs alignment. My goal is to have Onyx Design perfectly aligned with the right side of the navbar, or to have the navbar extend up to the end of "Onyx Design". The ...

Dealing with 'ECONNREFUSED' error in React using the Fetch API

In my React code, I am interacting with a third party API. The issue arises when the Avaya One-X client is not running on the target PC, resulting in an "Error connection refused" message being logged continuously in the console due to the code running eve ...

What is the best way to include a check mark icon using MUI or Tailwind CSS for every item selected in a dropdown menu?

I need help with adding a small check/tick icon next to the selected value, for example: Operations ✓ when the user chooses operations in the TopicList dropdown list. The TopicList is a class component used to retrieve data from the database which incl ...

Unable to retrieve data from Yahoo Finance using jQuery ajax

I am trying to develop a webpage that uses jQuery to make ajax requests in order to retrieve stock prices from a Yahoo web service. However, despite having a fast internet connection, I am not receiving any data from the following URL: http://ichart.financ ...

Difficulty with animated presentations

As a developer with limited CSS experience, I am trying to create a CSS3 slideshow using only two images. After discovering some interesting code for this purpose, which can be found here, I decided to make a small change to the original code (specifically ...

Encountering an Issue with AJAX Form Submission in CodeIgniter 4

I am currently working on saving records using AJAX Form Submit for CodeIgniter 4. Below is a snippet from my Controller code: namespace App\Controllers; use CodeIgniter\Controller; use App\Models\PeopleModel; class PreRegControll ...

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...