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

Submitted about 3 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.

application.js

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

tag.js

$(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(),
    colWidth;

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

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

CSS (this file is actually scss)

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

.affix-bottom {
  position: absolute;
}

View page

show.html.haml

.row
  .col-md-12
    %section.panel
      .panel-heading.stripe-4
        %h2.sec-filing-panel-title
          (Other code here)
      .panel-body
        - 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 }
          .filing-container
            - 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

tag_sidebar.html.haml

(Other code here)
...
  %tfoot
    %tr
      %td
        %a.well.well-sm{href: '#top'}
          %i.glyphicon.glyphicon-chevron-up
          Back to Top

Share This Post

Like this post? Star it on GitHub

Star It

See All Blog Posts