0

I'm trying to scroll to a div using a button, i'm using jquery & scrollTop for this, but the result isn't really precise and doesn't scroll to the correct position half the time... After searching for solutions, I found this answer which seemed to target my exact problem, however it doesn't work with my current structure and I can't figure out why.

Here's my current code :

$(document).ready(function() {
  $(".pabclick").click(function() {

    var ancre = '#' + $(this).attr('data-ancre');

    $('.pabmargin').stop().animate({
      scrollTop: $(ancre).offset().top +
        $('.pabmargin').scrollTop() -
        $('.pabmargin').offset().top
    }, 1000, function() {

    });
  });
});
.pabmargin {
  width: 300px;
  flex-grow: 1;
  max-height: 200px;
  overflow: auto;
  padding: 0 25px;
}
<script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>

<main>
  <div class="pabcontenu">
    <div id="contexte">
      <div class="pabmain">
        <div class="pabmargin">Text</div>
      </div>
    </div>
    <div id="reglement">

      <div class="pabmain">
        <div class="pabbann">
          <button class="pabclick" data-ancre="avatars">Avatars</button>
          <button class="pabclick" data-ancre="dcs">DCs</button>
        </div>
        <div class="pabmargin">

          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at accumsan massa. Nulla non nibh quis libero bibendum lacinia. Nam molestie blandit odio non varius. Vestibulum dignissim leo malesuada quam sodales, nec fermentum massa vehicula.
            Mauris iaculis augue orci, sit amet aliquam justo malesuada et. Aenean cursus, ante ut viverra sodales, ipsum risus suscipit lectus, vel ullamcorper est eros et ligula. Curabitur dapibus dictum ultrices. Morbi posuere justo neque, in egestas
            lorem efficitur sed. Mauris cursus nisl sit amet ante vulputate, et porta sem vulputate. Nam fringilla semper tellus eu faucibus. Mauris hendrerit metus tellus, non aliquet eros sagittis quis. Nullam mollis efficitur augue, fermentum egestas
            massa sodales eget. Praesent aliquet diam non augue gravida, efficitur mattis augue commodo. Cras nec fermentum magna, sit amet euismod augue. Proin sed ante sed ante luctus interdum vitae sit amet magna.</p>
          <p>Praesent placerat posuere massa, vel tincidunt purus auctor ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis vulputate ante dignissim libero pellentesque egestas. Cras laoreet dolor vitae erat
            pharetra, eu suscipit ex vehicula. Vestibulum in dui est. Cras eleifend, urna non tempus aliquet, magna massa tempus erat, id semper erat ipsum eget lorem. Nullam sed hendrerit tortor. Nulla id eleifend nisi. Etiam convallis neque odio, nec
            malesuada risus porttitor ac. Maecenas pulvinar sapien nec dui laoreet tempor. Curabitur velit lectus, aliquam sit amet commodo ac, fringilla auctor sapien.</p>

          <h4 id="avatars">Avatars</h4>

          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at accumsan massa. Nulla non nibh quis libero bibendum lacinia. Nam molestie blandit odio non varius. Vestibulum dignissim leo malesuada quam sodales, nec fermentum massa vehicula.
            Mauris iaculis augue orci, sit amet aliquam justo malesuada et. Aenean cursus, ante ut viverra sodales, ipsum risus suscipit lectus, vel ullamcorper est eros et ligula. Curabitur dapibus dictum ultrices. Morbi posuere justo neque, in egestas
            lorem efficitur sed. Mauris cursus nisl sit amet ante vulputate, et porta sem vulputate. Nam fringilla semper tellus eu faucibus. Mauris hendrerit metus tellus, non aliquet eros sagittis quis. Nullam mollis efficitur augue, fermentum egestas
            massa sodales eget. Praesent aliquet diam non augue gravida, efficitur mattis augue commodo. Cras nec fermentum magna, sit amet euismod augue. Proin sed ante sed ante luctus interdum vitae sit amet magna.</p>
          <p>Praesent placerat posuere massa, vel tincidunt purus auctor ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis vulputate ante dignissim libero pellentesque egestas. Cras laoreet dolor vitae erat
            pharetra, eu suscipit ex vehicula. Vestibulum in dui est. Cras eleifend, urna non tempus aliquet, magna massa tempus erat, id semper erat ipsum eget lorem. Nullam sed hendrerit tortor. Nulla id eleifend nisi. Etiam convallis neque odio, nec
            malesuada risus porttitor ac. Maecenas pulvinar sapien nec dui laoreet tempor. Curabitur velit lectus, aliquam sit amet commodo ac, fringilla auctor sapien.</p>

          <h4 id="dcs">Doubles-comptes</h4>

          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at accumsan massa. Nulla non nibh quis libero bibendum lacinia. Nam molestie blandit odio non varius. Vestibulum dignissim leo malesuada quam sodales, nec fermentum massa vehicula.
            Mauris iaculis augue orci, sit amet aliquam justo malesuada et. Aenean cursus, ante ut viverra sodales, ipsum risus suscipit lectus, vel ullamcorper est eros et ligula. Curabitur dapibus dictum ultrices. Morbi posuere justo neque, in egestas
            lorem efficitur sed. Mauris cursus nisl sit amet ante vulputate, et porta sem vulputate. Nam fringilla semper tellus eu faucibus. Mauris hendrerit metus tellus, non aliquet eros sagittis quis. Nullam mollis efficitur augue, fermentum egestas
            massa sodales eget. Praesent aliquet diam non augue gravida, efficitur mattis augue commodo. Cras nec fermentum magna, sit amet euismod augue. Proin sed ante sed ante luctus interdum vitae sit amet magna.</p>
          <p>Praesent placerat posuere massa, vel tincidunt purus auctor ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Duis vulputate ante dignissim libero pellentesque egestas. Cras laoreet dolor vitae erat
            pharetra, eu suscipit ex vehicula. Vestibulum in dui est. Cras eleifend, urna non tempus aliquet, magna massa tempus erat, id semper erat ipsum eget lorem. Nullam sed hendrerit tortor. Nulla id eleifend nisi. Etiam convallis neque odio, nec
            malesuada risus porttitor ac. Maecenas pulvinar sapien nec dui laoreet tempor. Curabitur velit lectus, aliquam sit amet commodo ac, fringilla auctor sapien.</p>

        </div>

      </div>
    </div>
    <div id="groupes">
      <div class="pabmain">
        <div class="pabmargin">Text</div>
      </div>
    </div>
  </div>
</main>

EDIT : I simplified my code so hopefully it is easier to understand what it does; basically I made tabs using :target on links, so I need to use jquery to simulate anchors for my text inside the tabs, for example in the "Règlement" tab you can see where my problem is: when you're at the top, it scrolls properly to the h4 title specified by the button, but if you already scrolled a bit, it just goes back to top... It seems to be related to there being a previous div in .pabcontenu, if I take out #contexte, it works properly. But I can't take that div out I need it ahah

EDIT 2: It seems scrollTop() always returns 0 for some reason?

amy
  • 55
  • 7
  • 4
    I made a proper snippet. Please modify it so it is a [mcve] - it is currently impossible to see what I am doing due to not enough height and blue on black which is unreadable. Seems to work as expected though – mplungjan Jul 18 '23 at 12:19
  • I'm sorry for putting my whole code in there, I honestly thought it was the best thing to do, as when I took out divs it seemed to work properly. I simplified it to the best buggy example I could do and changed link color, sorry again – amy Jul 18 '23 at 12:43

1 Answers1

0

I figured out why scrollTop behaved the way it did! First, I checked scrollTop()'s value in the console and realized it stayed at 0 no matter how much I scrolled .pabmargin, so it was very odd. Also, when I erased part of my structure, the script worked perfectly. Connecting the two dots, I realized there was multiple .pabmargin divs in my code, and so scrollTop was applied to the first one, which had no scroll! So all I had to do was target the right .pabmargin div, so I ended up with this script:

    $(document).ready(function (){
        $(".pabclick").click(function (){
            var pabmargin = $(this).parent(".pabsommaire").next();
            var ancre = '#' + $(this).attr('data-ancre');
            
            $(pabmargin).stop().animate({
                scrollTop: $(ancre).position().top 
                + $(pabmargin).scrollTop()
                - $(pabmargin).position().top
                }, 1000, function() {
            });
                
        });
    });

which now works fine :) Just thought I'd share if someone ever gets the same issue.

amy
  • 55
  • 7