A JavaScript library for smoother color transitions
This project is no longer maintained. CSS now has built-in support for setting color-interpolation-method. Transitioning through the oklch
color space is a superior alternative to using this library.
sweep.js is a small JavaScript library (5kb zipped) that enables proper color transitions through the HSL and HUSL spaces. Ordinary CSS transitions and existing frameworks convert HSL colors to RGB before transitioning. sweep.js addresses this by letting you transition through the color spectrum.
I've written an in-depth post about the need for HSL transitions here.
As a bundle:
bower install -S sweep
As a standalone library:
<script src="//cdn.jsdelivr.net/sweep/latest/mainfile"></script>
...or just visit the repo.
Sweep's dependencies are bundled; all you have to do is include the script. Sweep is wrapped with UMD, so it will also work as a module in your system of choice.
Using sweep.js to transition an element's color is easy. Whenever you want to trigger an HSL sweep, call:
sweep(target, properties, fromColor, toColor[, options]);
target
: element that you wish to animateproperties
: CSS properties that you wish to animate (string or array of strings)fromColor
: initial color before the transitiontoColor
: final color after the transitionoptions
(optional) : an object that can set the following:
callback
: function to be called once the animation finishesdirection
: clockwise (1) or counterclockwise (-1)duration
: time (in ms) to complete the animationspace
: 'HSL', 'HUSL', or 'RGB'an animation object with pause
and resume
methods is returned, which can be used like this:
// starts the animation
var transition = sweep(target, properties, fromColor, toColor[, options]);
// stops the animation
transition.pause();
// resumes the animation
transition.pause();
//click
var ex1 = document.querySelector('#ex1');
ex1.addEventListener('click', function() {
sweep(ex1, 'backgroundColor', '#a8f', '#a8f', {direction: -1, duration: 2000});
}, false);
Click
//hover
var ex2 = document.querySelector('#ex2'), transition;
ex2.addEventListener('mouseenter', function() {
if (transition) transition.pause();
transition = sweep(ex2, 'backgroundColor', getStyle(ex2, 'background-color'), '#0fa');
}, false);
ex2.addEventListener('mouseleave', function() {
if (transition) transition.pause();
transition = sweep(ex2, 'backgroundColor', getStyle(ex2, 'background-color'), '#a8f');
}, false);
Hover