KPI Cards with Sparklines

Pattern: Each card shows a metric value, a trend arrow (colored by whether the change is good or bad for that metric), and a tiny sparkline rendered with Chart.js. The sparkline is a line chart with all axes, legends, and tooltips disabled.
Total Pageviews
8,847
12.3%
Unique Sessions
3,201
5.7%
Avg Duration
3m 05s
2.1%
Bounce Rate
42.3%
8.4%

How the Sparklines Work

Each sparkline is a standard Chart.js line chart with everything turned off except the line and a subtle fill. The key settings:

new Chart(ctx, {
    type: 'line',
    data: {
        labels: data.map((_, i) => i),     // dummy labels
        datasets: [{
            data: data,
            borderColor: color,
            borderWidth: 2,
            fill: true,
            backgroundColor: color + '20',  // 12% opacity fill
            pointRadius: 0,                  // no dots
            tension: 0.4                     // smooth curve
        }]
    },
    options: {
        responsive: false,                   // fixed size
        plugins: {
            legend: { display: false },
            tooltip: { enabled: false }
        },
        scales: {
            x: { display: false },
            y: { display: false }
        }
    }
});

Trend Arrow Logic

The color of the trend arrow depends on the polarity of the metric. For pageviews and sessions, going up is good (green). For bounce rate, going down is good (also green). For average duration, going down is bad (red).

// polarity: 'positive' means "up is good", 'negative' means "down is good"
function trendClass(changePercent, polarity) {
    if (polarity === 'negative') {
        // Lower is better (bounce rate)
        return changePercent < 0 ? 'good' : 'bad';
    }
    // Higher is better (pageviews, sessions, duration)
    return changePercent > 0 ? 'good' : 'bad';
}

function trendArrow(changePercent) {
    return changePercent >= 0 ? '\u25B2' : '\u25BC';  // ▲ or ▼
}
← Back to Module 07