Good day.

Task: to make an accordion with functionality, as on this site - https://smylhub.com/ . Why when clicking on the <a> scroll occurs in the wrong place (it is always different)? Tried to use plugins - the result is the same.

HTML:

 <pre> <ul class="accordeon_list"> <li class="accordeon_item active" id="ac_itm_1"> <a href="#" class="accordeon_trigger" id="ac_btn_1">click1</a> <span class="accordeon_inner">content</span> </li> <li class="accordeon_item" id="ac_itm_2"> <a href="#" class="accordeon_trigger" id="ac_btn_2">click2</a> <span class="accordeon_inner">content</span> </li> <li class="accordeon_item" id="ac_itm_3"> <a href="#" class="accordeon_trigger" id="ac_btn_3">click2</a> <span class="accordeon_inner">content</span> </li> </ul> </pre> 

Js:

 $(".accordeon_trigger").click(function (){ $('html, body').animate({ scrollTop: $(this).closest(".accordeon_item").offset().top }, 2000); }); 
  • @Crantisz is the code for the accordion itself: $ ('. Accordeon_trigger'). On ('click', function (e) {e.preventDefault (); var $ this = $ (this), item = $ this.closest ('. accordeon_item '), list = $ this. '); if (! item.hasClass (' active ')) {otherContent.stop (true) .slideUp (400); content.stop (true) .slideDown (400); items.removeClass (' active '); item .addClass ('active');}}); - extens
  • Add code to the question. Click "Edit" - Crantisz
  • In principle, I have already answered, only there will be 400 ms the length of the delay, and not 1000. - Crantisz

1 answer 1

First, disable the anchor jump by adding return false to the end of the event handler:

 $(".accordeon_trigger").click(function (){ ... return false; }); 

Second, you didn't write all the code, and I can only guess. As I understand it, you are trying to immediately adjust the scroll to the desired position:

 scrollTop: $(this).closest(".accordeon_item").offset().top 

Before that, you assigned some kind of animation with blocks, some block is hidden, some appears, and for some reason you decided that offset() will not return the current coordinates to you , but will predict some coordinates from the future.

But the fact is that virtually no changes have yet happened, and where the offset().top after the block animation is completed is not known .

Decision

1) You need to either wait for the changes to take effect:

 $(".accordeon_trigger").click(function (){ setTimeout(function(){ $('html, body').animate({ scrollTop: $(this).closest(".accordeon_item").offset().top }, 2000); }), 1000) //1000 - Π΄Π»ΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΡŒ Π°Π½ΠΈΠΌΠ°Ρ†ΠΈΠΈ с Π±Π»ΠΎΠΊΠ°ΠΌΠΈ }); 

( setTimeout , not delay !)

2) Either subtract the height of the hidden block and add the height of the block that appears