Scrolling sidebar and Back To Top with JQuery Haml Bootstrap Affix in Rails

Submitted over 5 years Ago

Share This Post

The other day I implemented some page interaction where the user can scroll the content in the page sidebar up and down. Also, when they have scrolled below view, they can click a button to go back to the top of the page. This had to work together with a separate content section on the right side which also scrolled. The view page is in HAML. The jQuery is delivered via the Bootstrap Affix plugin.

It was a bit of a dance getting all this to work together properly and getting it to render in HAML within the Ruby on Rails app. It also had a few partials and separate style sheets already. Here are some notes on what eventually worked. I've removed sections of the files that do not apply to these features.

It was tricky getting the spacing of the Back To Top button to work with the existing footer. Playing around with a few options when you get to the bottom of the page will tell you where you need to adjust.


//= require jquery
//= require jquery_ujs
(More Code Here)
//= require tag


$(document).ready(function () {
    $('.ds-tag').on('mousedown', highlight_tag);
// Change the selector if needed
var $table = $('table.scroll'),
    $bodyCells = $table.find('tbody tr:first').children(),

//// Adjust the width of thead cells when window resizes
$(window).resize(function() {
    // Get the tbody columns width array
    colWidth = $ {
        return $(this).width();

    // Set the width of thead columns
    $table.find('thead tr').children().each(function(i, v) {
}).resize(); // Trigger resize handler

CSS (this file is actually scss)

.affix {
  position: fixed;
  top: 73px;

.affix-bottom {
  position: absolute;

View page


          (Other code here)
        - if @filing.sec_filing_text.tagged_html.present?
          .tags-container.affix{data: {'offset-top': '100', 'offset-bottom': '150','spy': 'affix'}}
            =render partial: 'tag_sidebar', locals: { filing: @filing }
            - if @filing.sec_filing_text.tagged_html.present?
              = @filing.sec_filing_text.tagged_html.html_safe

View page partial, for the sidebar that has the Back To Top button


(Other code here)
        %a.well.well-sm{href: '#top'}
          Back to Top

Share This Post

Like this post? Star it on GitHub

Star It

See All Blog Posts