Code for accordion. When clicking on ul.akkordeon1 li > p a block with text is opened, and ul.akkordeon1 li > p added to the active class, when clicking on an inactive block, the active class is deleted and the block with open content is hidden; this causes the page to be thrown volume in content. This moment can be ul.akkordeon1 li > p.active by ul.akkordeon1 li > p.active page to the beginning of the element with the class ul.akkordeon1 li > p.active , but the code that I have listed below does not work.

 $('ul.akkordeon1 li > p').click(function(){ if(!$(this).hasClass('active')) { //Ссли "ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚Ρ‹ΠΉ" ΠΏΡƒΠ½ΠΊΡ‚ Π½Π΅Π°ΠΊΡ‚ΠΈΠ²Π½Ρ‹ΠΉ: $('ul.akkordeon1 li > p').removeClass('active').next('div').slideUp(); //Π΄Π΅Π»Π°Π΅ΠΌ Π½Π΅Π°ΠΊΡ‚ΠΈΠ²Π½Ρ‹ΠΌΠΈ всС ΠΏΡƒΠ½ΠΊΡ‚Ρ‹ ΠΈ скрываСм всС Π±Π»ΠΎΠΊΠΈ $(this).addClass('active'); //Π°ΠΊΡ‚ΠΈΠ²ΠΈΡ€ΡƒΠ΅ΠΌ "ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚Ρ‹ΠΉ" ΠΏΡƒΠ½ΠΊΡ‚ $(this).next('div').slideDown(200); //раскрываСм ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΉ Π·Π° Π½ΠΈΠΌ Π±Π»ΠΎΠΊ с описаниСм $("body").animate({ scrollTop:$('ul.akkordeon1 li > p.active').offset().top}, 600); //ΠΏΠ»Π°Π½ΠΈΡ€ΠΎΠ²Π°Π»ΠΎΡΡŒ Ρ‡Ρ‚ΠΎ ΠΏΡ€ΠΈ ΠΎΡ‚ΠΊΡ€Ρ‹Ρ‚ΠΈΠΈ Π½ΠΎΠ²ΠΎΠΉ сСкции экран Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΡ€ΠΎΠΊΡ€ΡƒΡ‡ΠΈΠ²Π°Ρ‚ΡŒΡΡ ΠΊ p.active Π½ΠΎ это Π½Π΅ происходит } else { //ΠΈΠ½Π°Ρ‡Π΅: $(this).removeClass('active').next('div').slideUp(); //скрываСм Π΄Π°Π½Π½Ρ‹ΠΉ ΠΏΡƒΠ½ΠΊΡ‚ } }); 

    2 answers 2

    This is how you want to determine where the element is located:

     $('ul.akkordeon1 li > p.active').offset().top 

    The problem is that you hide the menu item using slideUp() , which means that the changes have not actually happened yet. Those. that block which should disappear, in fact, just started to do it and is not yet hidden. Ie as I understand it, you need to subtract its height:

     $('ul.akkordeon1 li > p.active').offset().top-$('ul.akkordeon1 li > p').removeClass('active').next('div').height() 

    Plus, the speed difference. a block of 400 ms is hidden (standard for slideUp ), and the scrolling animation you make is 600ms. Those. she does not have time.

    So the animation may not work due to the fact that you have prescribed $("body") , you need this:

      $("html, body").animate({ scrollTop: .. },400); 

    This is necessary for maximum support by different browsers.

      Working code

       $('ul.akkordeon1 li > p').click(function(){ //Ссли "ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚Ρ‹ΠΉ" ΠΏΡƒΠ½ΠΊΡ‚ Π½Π΅Π°ΠΊΡ‚ΠΈΠ²Π½Ρ‹ΠΉ: if(!$(this).hasClass('active')){ //Π΄Π΅Π»Π°Π΅ΠΌ Π½Π΅Π°ΠΊΡ‚ΠΈΠ²Π½Ρ‹ΠΌΠΈ всС ΠΏΡƒΠ½ΠΊΡ‚Ρ‹ ΠΈ скрываСм всС Π±Π»ΠΎΠΊΠΈ $('ul.akkordeon1 li > p').removeClass('active').next('div').hide(); //Π°ΠΊΡ‚ΠΈΠ²ΠΈΡ€ΡƒΠ΅ΠΌ "ΠΊΠ»ΠΈΠΊΠ½ΡƒΡ‚Ρ‹ΠΉ" ΠΏΡƒΠ½ΠΊΡ‚ $(this).addClass('active'); //раскрываСм ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΉ Π·Π° Π½ΠΈΠΌ Π±Π»ΠΎΠΊ с описаниСм $(this).next('div').slideDown(600); } else { //ΠΈΠ½Π°Ρ‡Π΅: //скрываСм Π΄Π°Π½Π½Ρ‹ΠΉ ΠΏΡƒΠ½ΠΊΡ‚ $(this).removeClass('active').next('div').slideUp(); } $("html,body").animate({ scrollTop:$('ul.akkordeon1 li > p.active').offset().top - 80}, 600); });