Guys, made a scroll in a modal window and made an anchor in the tabs menu, it should have turned out that when you click on a certain tab, the content smoothly went down or up but it turned out that when I click on the second tab, the content abruptly goes down in the same way as with the first tab and one more error that the action can be performed only once and then the tabs do not work until the page is reloaded. What have I done wrong

$(document).ready(function(){ $("#menu").on("click","a", function (event) { event.preventDefault(); var id = $(this).attr('href'), top = $(id).offset().top; $('body,html').animate({scrollTop: top}, 1500); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="main"> <section id="tab1"> <video class="videocontent" controls poster="images/preview.jpg"> <source src="images/ps.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> </video> </section> <section id="tab2"> <img src="images/background.jpg"> </section> </div> <div class="leftcol"> <img class="img1" src="images/ps4.jpg"> <img class="img2" src="images/logo.jpg"> <div class="tabs" id="menu"> <ul class="nav"> <li class="nav_item"> <a href="#tab1">Video</a> </li> <li class="nav_item"> <a href="#tab2">Horizon Zero Dawn</a></br> </li> <li class="nav_item"> <a href="#tab3">Through Aloy's Eyes</a> </li> </ul> </div> </div> 

  • jsfiddle.net/vmtye285 smooth transition on your code works ... Or what's the problem? Ctrl + F5 tried? - Oleksandr
  • jsfiddle.net/vmtye285/3 look at my full code, for some reason I don’t work @Oleksandr - Calvin
  • You get an error that there is no element with id tab3 . Well, the idea of ​​scrolling can work only if there is much to scroll, the content is greater than the height of the window and the scrollbar appeared - Crantisz
  • @Crantisz and how to write this jquery function in pure javascript? - Calvin

1 answer 1

You have three mistakes.

1. You get an error that there is no element with id tab3 . Although it is rather just a shortcoming

2. Scrolling in theory can work only if there is much to scroll, the content is greater than the height of the window and a scrollbar appears. I added height:

 .main section{ min-height:600px; } 

3.If you need to scroll not the page itself, but content in some part of it, you need to call animate() scroll-top from this part, and not from the body :

  $('.main').animate({scrollTop: top}, 1500); 

https://jsfiddle.net/vmtye285/4/

  • and how to write it all in pure javascript without using jquery? - Calvin
  • If you have a new question, ask it using the " Ask a Question " button. If you need to specify the context, give a link to this question. - Crantisz
  • That's great, do not interfere with these two questions - Crantisz