JQuery slideToggle delayed animation

I have a regular accordion menu. To display the second level options in the menu, I decided to use slideToggle() . For some reason, there is a delay between the click and the animation.

enter image description here

This can be seen if you look, unlike the other accordion menus on the same page ... I found out that the function associated (by clicking) with the menu item is executed almost immediately. The problem is that the slideToggle animation seems to start later than it should.

I believe this may be due to the way I aim at the element that slideToggle() calls.

  var $expandableMenu = $(".expandable .level1"); $expandableMenu.bind('click', function () { $(this).next().slideToggle(200, function () { $(this).parent().toggleClass("opened"); }); }); 

Maybe the problem is that $(this).next() is a slow way to target the element that I need to use slideToggle() on?

What are your thoughts?

Edit: I made a test case of jsFiddle ... Oddly enough, the problem does not occur here. http://jsfiddle.net/nYZNP Still looking for a problem.

+6
source share
2 answers

If you are trying to do this on a mobile device, it may take longer to start the animation since the device is waiting (even 200 ms +) to make sure that you are not trying to double-tap. If so, you can go to libraries like zepto.js , which has a tap event or fastclick.js , which emulates click events.

in terms of selector performance, $(this).parent() should be fine. In this case, however, you could eliminate a few milliseconds without writing or reading the variable first, for example:

  $(".expandable .level1").bind('click', function () { $(this).next().slideToggle(200, function () { $(this).parent().toggleClass("opened"); }); }); 

In addition, "As with jQuery 1.7, the .on () method is the preferred method for attaching event handlers to a document." ( jQuery api ). Or, in other words, bind() deprecated!

And finally, there is a general rule according to which filtering by tag name is faster than by class name or id, so $("li.expandable .level1") should be faster than $(".expandable .level1") .

Perhaps you can also be more specific regarding specific circumstances, such as a browser / device or any other difference from your violin?

+1
source
  $(this).next().slideToggle(200, "linear", function () { $(this).parent().toggleClass("opened"); }); 

Have you tried using a different easing method?

Also, if you experience this on a mobile device, the delay may be part of how mobile devices handle click events, which may have an inherent delay of 50 ms or more.

0
source

Source: https://habr.com/ru/post/950763/


All Articles