AndrewMantarro
9/11/2017 - 12:23 AM

Module Javascript - this makes the accordion feature and responsive tables work

Module Javascript - this makes the accordion feature and responsive tables work

<script>

$('.accordion td:last-child').wrapInner('<div class="expand" />');

$( ".accordion tr" ).each(function() {
  $(this).click(function() {
    $(this).toggleClass('on');
  });
});
  
$('.overflowTable').wrap('<div class="scrollTable" style="overflow-x:auto;"/>');

$( ".responsiveTable tr:first-child td" ).each(function() {
  
  $( this ).replaceWith( "<th>" + $( this ).text() + "</th>" );
  
});

(function ResponsiveTableBuilder($) {
    this.tables = [];
    this.css = "@media screen and (max-width: 700px) { ";

    this.getTablesAndHeadings = function () {
        var self = this;
        // for each of the tables on the page...
        $('.responsiveTable').each(function () {
            var obj = { e: this, headings: [] };
            // store table headings
            var headers = this.getElementsByTagName('th');
            $(headers).each(function () {
                obj.headings.push(this.textContent);
            });
            self.tables.push(obj);
        });
    };

    this.buildCSS = function () {
        var tableCount = 0;
        var self = this;
        for (var t = 0; t < this.tables.length; t++) {
            var table = self.tables[t];
            // add a class to identify individual tables
            table.e.className += "t_" + tableCount;
            // for each header, add the header to the corresponding cell's content of the :before pseudo-element
            for (var i = 0; i < table.headings.length; i++) {
                self.css += ".respondTablet_" + tableCount + " tr td:nth-of-type(" + (i + 1) + "):before { content: '" + table.headings[i] + "'; } ";
            }
            tableCount++;
        };

        // create style tag
        var style = document.createElement('style');
        style.type = "text/css"
        // closing media query
        self.css += " }";
        // fill style tag with css
        if (style.styleSheet) {
            style.styleSheet.cssText = self.css;
        } else {
            style.appendChild(document.createTextNode(self.css));
        }
        // append style tag to document head
        var head = document.head || document.getElementsByTagName("head")[0];
        head.appendChild(style);
    };
    
    this.getTablesAndHeadings();
    this.buildCSS();

})(jQuery);

</script>