How do I make an anchor with a floating padding on top?

  • 0
    When you click on the link, the page scrolls to the anchor, but on the page there is a floating horizontal menu (hidden when scrolling up) + fixed. It turns out that if I indent only the fixed menu, when scrolling down, the floating menu appears and closes the beginning of the content, when scrolling up all the rules, and if I indent, taking into account the floating menu, then when scrolling up, top remains too large.

    How do I make sure that when scrolling down, the margin is 200px, and up - 100 px from the anchor?

    I use the following code to scroll.
    $(document).ready(function(){
      $("#menu").on("click","a", function (event) {
      event.preventDefault();
      var div = $(this).attr('href'),
      top = $(div).offset().top - 100;
    	  
      $('body,html').animate({scrollTop: top}, 1000);
      });
      
    });
    JavaScript Hunter Andrade, Jun 6, 2020

  • 1 Answers
  • 0
    top = $ (div) .offset (). top - 100;



    you have a scroll up to this position (top value), experiment



    upd: I read it inattentively, compare the current position and if $ (div) .offset (). top is less than the current one, that is, scroll up, then -100, if more, that is, scroll down, then -200



    upd2: js not in practice, but there should be something like this:
    $(document).ready(function(){
    $("#menu").on("click","a", function (event) {
    event.preventDefault();
    var div = $(this).attr('href');
    var top = $(div).offset().top;
    var pos = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

    var delta = (top > pos) ? 200 : 100;

    top = top-delta;
    $('body,html').animate({scrollTop: top}, 1000);
    });

    });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!