Getting Started with BlackMagic.js
BlackMagic.js is the world's first truly automatic dark mode framework. It requires zero configuration and automatically ensures WCAG 2.1 accessibility compliance.
Installation
NPM Installation
npm install blackmagic-js
import BlackMagic from 'blackmagic-js';
const darkMode = new BlackMagic();
darkMode.toggle();
CDN Installation
<script src="https://cdn.jsdelivr.net/npm/blackmagic-js@latest"></script>
<script>
const blackMagic = new BlackMagic();
blackMagic.toggle();
</script>
Basic Usage
The simplest way to add dark mode to your website:
// Initialize BlackMagic
const blackMagic = new BlackMagic();
// Toggle between light and dark themes
document.getElementById('darkModeToggle').addEventListener('click', () => {
blackMagic.toggle();
});
Configuration Options
BlackMagic.js works perfectly with zero configuration, but you can customize it:
const blackMagic = new BlackMagic({
backgroundColor: '#1a1a1a', // Custom dark background color
factor: 0.4, // Color adjustment intensity (0-1)
themeClass: 'custom-dark', // Use CSS class instead of inline styles
cookieName: 'theme', // Custom cookie name
cookieDuration: 365, // Cookie expiration in days
localStorageKey: 'darkmode', // Custom localStorage key
autoSwitch: true, // Apply saved theme on page load
currentTheme: 'light' // Initial theme ('light' or 'dark')
});
Configuration Details
- backgroundColor: The background color used in dark mode (default: '#000')
- factor: How aggressively to adjust colors (0.1-1.0, default: 0.4)
- themeClass: CSS class to add to body instead of inline styles
- cookieName: Name for the cookie that stores theme preference
- cookieDuration: How long to remember user's choice (days)
- localStorageKey: localStorage key for theme persistence
- autoSwitch: Whether to automatically apply saved theme
- currentTheme: Initial theme state
API Reference
Methods
toggle()
Switches between light and dark themes.
blackMagic.toggle();
applyTheme(theme)
Applies a specific theme ('light' or 'dark').
blackMagic.applyTheme('dark');
blackMagic.applyTheme('light');
getCurrentTheme()
Returns the current theme ('light' or 'dark').
const currentTheme = blackMagic.getCurrentTheme();
console.log(currentTheme); // 'light' or 'dark'
saveTheme(theme)
Saves theme preference to cookies and localStorage.
blackMagic.saveTheme('dark');
getStoredTheme()
Retrieves saved theme preference.
const savedTheme = blackMagic.getStoredTheme();
console.log(savedTheme); // 'light', 'dark', or null
Advanced Usage
Using with CSS Classes
Instead of inline styles, you can use CSS classes:
const blackMagic = new BlackMagic({
themeClass: 'dark-theme'
});
body.dark-theme {
background-color: #1a1a1a;
color: #e0e0e0;
}
body.dark-theme .card {
background-color: #2a2a2a;
border-color: #404040;
}
Custom Color Adjustment
Fine-tune how aggressively colors are adjusted:
// Subtle adjustment (good for websites with light backgrounds)
const subtle = new BlackMagic({ factor: 0.2 });
// Standard adjustment (balanced, recommended)
const standard = new BlackMagic({ factor: 0.4 });
// Aggressive adjustment (good for websites with many colors)
const aggressive = new BlackMagic({ factor: 0.7 });
Multiple Instances
You can create multiple BlackMagic instances with different configurations:
// Main site dark mode
const mainDarkMode = new BlackMagic({
backgroundColor: '#1a1a1a',
cookieName: 'site-theme'
});
// Modal dark mode with different settings
const modalDarkMode = new BlackMagic({
backgroundColor: '#2d1b69',
factor: 0.6,
autoSwitch: false
});
Browser Support
BlackMagic.js works across all modern browsers:
- ✅ Chrome 60+
- ✅ Firefox 60+
- ✅ Safari 12+
- ✅ Edge 79+
- ✅ Opera 47+
- ✅ Samsung Internet 8.2+
Feature Detection
BlackMagic.js includes graceful fallbacks:
- localStorage unavailable → Falls back to cookies
- Cookies disabled → Theme persists for session only
- CSS support limited → Basic color adjustments still work
Accessibility
BlackMagic.js is designed with accessibility as a core feature:
WCAG 2.1 Compliance
- Automatically maintains 4.5:1 contrast ratios for normal text
- Ensures 3:1 contrast ratios for large text
- Preserves focus indicators and interactive element visibility
- Compatible with screen readers and assistive technologies
Color Science
BlackMagic uses advanced color algorithms:
- HSL color space manipulation for natural adjustments
- Luminance calculations with gamma correction
- Perceptual color distance measurements
- Brand color preservation through hue retention
Performance
BlackMagic.js is optimized for speed and efficiency:
Benchmarks
- Color calculation time: <50ms for 1000+ elements
- Memory usage: <2MB additional overhead
- Bundle size: 8KB minified, 3KB gzipped
- Dependencies: Zero external dependencies
Optimization Features
- Intelligent DOM traversal with early exit conditions
- Color calculation caching to avoid redundant work
- Debounced theme switching to prevent rapid toggles
- Lazy evaluation of color adjustments
Troubleshooting
Common Issues
Dark mode doesn't apply to all elements
This usually happens when elements have very specific CSS selectors. Try increasing the factor:
const blackMagic = new BlackMagic({ factor: 0.6 });
Theme doesn't persist across pages
Make sure cookies are enabled and you're not in incognito mode. Check your cookie settings:
const blackMagic = new BlackMagic({
cookieDuration: 365, // Persist for 1 year
cookieName: 'custom-theme-name'
});
Performance issues on large pages
For pages with thousands of elements, consider using CSS classes:
const blackMagic = new BlackMagic({
themeClass: 'dark-mode' // Use CSS instead of inline styles
});
Debug Mode
Enable console logging to debug issues:
// Check current theme
console.log('Current theme:', blackMagic.getCurrentTheme());
// Check stored theme
console.log('Stored theme:', blackMagic.getStoredTheme());
// Check if cookies work
document.cookie = 'test=value';
console.log('Cookies enabled:', document.cookie.includes('test=value'));
Migration Guide
From CSS-based Dark Mode
Replace manual CSS with BlackMagic:
/* Remove hundreds of lines like this */
.dark-mode .button { color: #fff; background: #333; }
.dark-mode .text { color: #e0e0e0; }
.dark-mode .card { background: #2a2a2a; }
// Replace with 3 lines
const blackMagic = new BlackMagic();
button.addEventListener('click', () => blackMagic.toggle());
From Other Dark Mode Libraries
BlackMagic.js uses similar API patterns:
// Most libraries
darkMode.toggle();
// BlackMagic (same API!)
blackMagic.toggle();
Contributing
BlackMagic.js is open source and welcomes contributions!
Development Setup
git clone https://github.com/LucAngevare/BlackMagic-js.git
cd BlackMagic-js
npm install
npm run dev
Contributing Guidelines
- Read the CONTRIBUTING.md file
- Check existing issues before creating new ones
- Write tests for new features
- Follow the existing code style
- Update documentation for API changes
Reporting Issues
Found a bug? Report it on GitHub with:
- Browser and version
- BlackMagic.js version
- Minimal reproduction example
- Expected vs actual behavior