Anchor link and anchor target in different scrolling divs

时间:2017-10-12 10:07:07

标签: javascript jquery scroll anchor anchor-scroll

I have an article with footnotes. The footnotes are in a fixed and scrollable div next to the article. They are structured in two columns (article on the left, footnotes on the right).

I would like to have a scroll effect both in the anchors in the article pointing to the footnotes and the anchors in the footnotes pointing to the article. Only the div with the target anchor should scroll.

For example if I click on a superscript number in the article the footnotes div should scroll and position the relative footnote on the top of the page. Similarly, if I click on a footnote number the body should scroll and position the relative superscript number on the top of the page.

This an example of HTML + CSS:

<div class="article" style="position:relative; left:0px; top:0px; width:50%; height:100%; ">
  <!-- other text -->
  <p>Text <a id="1" href="#1_ref">1</a></p>
  <!-- other text -->
</div>

<div class="footnotes" style="position:fixed; left:50%; top:0px; width:50%; height:100%; overflow:scroll;">
  <!-- several other footnotes -->
  <p><a id="1_ref" href="#1">1</a> Footnote</p>
  <!-- several other footnotes -->
</div>

This is my JS:

$(document).ready(function(){
  $("a").on('click', function(event) { 
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){
        window.location.hash = hash;
      });
    } 
  });
});

When I click on an anchor link in the right column the left one scrolls positioning the right anchor target on the top of the page. The problem is when I do the opposite. If I click on an anchor link on the left column the same column scrolls up and then the right one jumps to the anchor target. It seems that the left column scrolls up the same amount of pixels of the distance from the anchor target on the right column and the top of the same column.

Anyone who knows how to make it work?

0 个答案:

没有答案