Theming — Dynamic Colors

Apply colors at runtime based on data or rules.

Change Timeline Colors Based on URL Parameters Reset URL

View the page source and read the Javascript code to see how it was done.

Javascript code:


// capture URL parameters
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());

document.addEventListener('DOMContentLoaded', function () {

  // load some data
  var items = [
    { id: 1, date: '01/01/24', heading: 'Init', summary: 'Project start' },
    { id: 2, date: '02/01/24', heading: 'Build', summary: 'Development work' },
    { id: 3, date: '05/01/24', heading: 'Ship', summary: 'Release' },
    { id: 4, date: '06/01/24', heading: 'Support', summary: 'Product Support' },
    { id: 5, date: '06/01/24', heading: 'Sales', summary: 'Ongoing Sales' }
  ];

  // set default colors
  var nodeColor = '#2196F3';
  var lineColor = '#64B5F6';

  // variables for new colors
  var newNodeColor = normalizeHexColor(params.newNodeColor);
  var newLineColor = normalizeHexColor(params.newLineColor);

  // if we have new values
  if (newNodeColor && newLineColor) {
    // use the new colors
    timelineFromData('#theme-tl', items, { mode: 'horizontal', nodeColor: newNodeColor, lineColor: newLineColor });
  } else {
    // otherwise, use default colors
    timelineFromData('#theme-tl', items, { mode: 'horizontal', nodeColor: nodeColor, lineColor: lineColor });
  }

  // validate color values being passed
  // if they aren't valid, use default values
  function normalizeHexColor(val) {
    if (!val) return null;
    var cleaned = val.trim().replace(/^#/, '');
    if (!/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(cleaned)) return null;
    return '#' + cleaned;
  }

});