jQuery: 'back to top' links

Creating 'back to top' links with jQuery requires only a basic knowledge of some DOM traversal methods provided by jQuery. First of all, let's say that we have some headings followed by a series of paragraphs. We want to insert a 'back to top' link just after the last paragraph of each series. Our HTML structure is the following:

<div id="content">
  <h2>...</h2>
  <!--paragraphs-->
  <h2>...</h2>
  <!--paragraphs-->
</div>

We want to turn the above structure into this one:

<div id="content">

  <h2>...</h2>
  
  <div class="section">
  
    <!--paragraphs-->
    
    <div class="top">
    
     <a href="#content">Back to top</a>
    
    </div>
  
  </div>
  
  <h2>...</h2>
  
  <div class="section">
  
    <!--paragraphs-->
    
    <div class="top">
    
     <a href="#content">Back to top</a>
    
    </div>
  
  </div>



</div>

Here's the jQuery code:

$(document).ready(function() {

  var link = '<div class="top">' +
             '<a href="#content">' +
             'Back to top ' + '</a>' +
             '</div>';
  
  $('#content h2').each(function() {
  
    var $h2 = $(this);
    
    $h2.nextUntil('h2').wrapAll('<div class="section"></div>'); 
  
  });
  
  $('div.section').each(function() {
  
    var $section = $(this);
    
    $(link).appendTo($section);
  
  });
    
});

We select all the paragraphs that follow each heading with the nextUntil() method, which returns a new wrapped set containing all the subsequent siblings of an element except the element specified in the method. Then we wrap these elements using the wrapAll() method. Finally, we loop through the newly created page sections and we append our link to them. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.