Lesson 2 of 9
Data Attributes & Canvas
Data attributes (data-*) let you store custom data on any HTML element. The Canvas API lets you draw 2D graphics, charts, and animations programmatically. Together they power interactive dashboards, games, and data visualizations.
Custom Data Attributes
Any attribute starting with data- stores custom data on elements. Access via element.dataset.propertyName in JavaScript (data-user-id becomes dataset.userId). Use for: component configuration, tracking IDs, dynamic content, and storing state without polluting global scope. Data attributes are valid HTML - unlike custom non-standard attributes, they pass validation.
Store custom data on DOM elements cleanly without breaking HTML validation
Data Attributes & Canvas Code
<!-- Data attributes in HTML -->
<div class="product-card"
data-product-id="42"
data-price="29.99"
data-category="electronics"
data-in-stock="true">
<h3>Wireless Mouse</h3>
<button onclick="addToCart(this.closest('[data-product-id]'))">
Add to Cart
</button>
</div>
<script>
// Reading data attributes
const card = document.querySelector('.product-card');
console.log(card.dataset.productId); // "42"
console.log(card.dataset.price); // "29.99"
console.log(card.dataset.inStock); // "true"
// Canvas: draw a simple chart
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
// Bar chart
const data = [65, 85, 45, 95, 70];
const labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
const barWidth = 40;
const gap = 20;
data.forEach((value, i) => {
const x = i * (barWidth + gap) + 30;
const height = value * 2;
const y = canvas.height - height - 30;
// Draw bar
ctx.fillStyle = '#E44D26';
ctx.fillRect(x, y, barWidth, height);
// Draw label
ctx.fillStyle = '#333';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(labels[i], x + barWidth / 2, canvas.height - 10);
ctx.fillText(value + '%', x + barWidth / 2, y - 5);
});
</script>Tip
Use data attributes with CSS for simple state management without JavaScript. The CSS selector [data-status='active'] lets you style elements based on their data attribute values. Combined with :hover and transitions, you can build interactive UI components with minimal JS.
Quick Quiz: Data Attributes & Canvas
Finished this lesson?