Search code examples
javascriptfootnotes

How to do back to footnote for different anchor elements using JavaScript?


I am having three different anchor links with unique ID, I wanted to make footnote to some other links on the same page.But I am facing issue with Back to Footnote is same for all the three anchor links.

<sup><a href="#one">One&nbsp;&Dagger;</a></sup><br/>
<sup><a href="#two">Two&nbsp;&Dagger;</a></sup><br/>
<sup><a href="#three">Three&nbsp;&Dagger;</a></sup>
  <br/>
  <br/>
  <br/>
  <br/>
  <br/><br/><br/><br/><br/><br/>
  <a href="#" id="one">&#x21B5;Back to footnote</a>

How do I make back to footnote reference to above anchors like "one", "two", "three" respectively.

Any help would be appreciated...thanks!!!


Solution

  • If I understood your question correctly, you want the links to go down to the "Back to footnote" link, then you want that "Back to footnote" link to go back to the link you've clicked on. If I'm wrong on the interpretation of your question, do comment and I'll adjust.

    Basically, I've added an event listener to each links where when you click it changes the "Back to footnote" href to the correct anchor:

    var $anchors = document.getElementsByClassName('anchor');
    var $footnote = document.getElementById('footnote');
    
    for (var i = 0; i < $anchors.length; i++) {
      var $anchor = $anchors[i];
      
      $anchor.addEventListener('click', function () {
        $footnote.href = '#' + this.id;
      });
    }
    <sup><a id="one" class="anchor" href="#footnote">One&nbsp;&Dagger;</a></sup>
    <br><br><br>
    <sup><a id="two" class="anchor" href="#footnote">Two&nbsp;&Dagger;</a></sup>
    <br><br><br>
    <sup><a id="three" class="anchor" href="#footnote">Three&nbsp;&Dagger;</a></sup>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <a href="#" id="footnote">&#x21B5;Back to footnote</a>

    jQuery

    $('.anchor').click(function() {
      $('#footnote').attr('href', '#' + this.id);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <sup><a id="one" class="anchor" href="#footnote">One&nbsp;&Dagger;</a></sup>
    <br><br><br>
    <sup><a id="two" class="anchor" href="#footnote">Two&nbsp;&Dagger;</a></sup>
    <br><br><br>
    <sup><a id="three" class="anchor" href="#footnote">Three&nbsp;&Dagger;</a></sup>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <a href="#" id="footnote">&#x21B5;Back to footnote</a>