Table with Sticky Header

by spacejack

Level: beginner • Mithril.js Version: latest

This example shows how to create a table with a sticky header. The table is filled with randomized fake data, the sticky behavior is made with pure CSS.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

CSS

.sticky-table {
  display: inline-block;
  max-height: 30em;
  overflow-x: hidden; /* Prevent Firefox h-scrollbar */
  overflow-y: auto;
  border: #666 1px solid;
  border-collapse: collapse;
}

.sticky-table th {
  text-align: left;
  position: sticky;
  top: 0;
  background-color: #DDD;
}

.sticky-table td {
  padding-right: 1em; /* Prevent Firefox overlap scrollbar */
}

JavaScript

function range(n) {
  return Array.from(Array(n).keys())
}

const randText = (function(){
  const letters = 'abcdefghijklmnopqrstuvwxyz '
  return function randText() {
    const len = 3 + Math.floor(Math.random() * 12)
    let s = ''
    for (let i = 0; i < len; ++i) {
      s += letters[Math.floor(Math.random() * letters.length)]
    }
    return s
  }
}())

const rows = 75
const cols = 5

const data = range(rows).map(() => range(cols).map(randText))

const StickyTable = {
  view() {
    return m('table.sticky-table',
      m('thead',
        m('tr',
          range(cols).map(c => m('th', randText()))
        )
      ),
      m('tbody',
        data.map(row => m('tr',
          row.map(col => m('td', col))
        ))
      )
    )
  }
}

m.mount(document.body, StickyTable)

The snippet is using the most current version of Mithril.js framework. It is aimed at beginners and shows some basic recipes.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method.

The example was contributed by spacejack and last modified on 24 October 2021. Click here to see more examples contributed by the author.

Contribute

If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub