jquery.adaptive-backgrounds.js
🦎 A jQuery plugin for extracting the dominant color from images and applying the color to their parent.
Top Related Projects
Grab the color palette from an image using just Javascript. Works in the browser and in Node.
Fast, small color manipulation and conversion for JavaScript
Extract prominent colors from an image. JS port of Android's Palette.
Quick Overview
jquery.adaptive-backgrounds.js is a jQuery plugin that extracts the dominant color from images and applies it to their parent containers. This creates a visually appealing effect where the background color of an element adapts to match the primary color of the image it contains.
Pros
- Easy to implement with minimal code
- Enhances visual aesthetics of web pages
- Works with various image formats
- Customizable with options for color selection and application
Cons
- Requires jQuery, which may not be ideal for modern web development
- Limited maintenance (last updated in 2017)
- May impact performance on pages with many images
- Potential accessibility issues if not implemented carefully
Code Examples
- Basic usage:
$(document).ready(function(){
$.adaptiveBackground.run()
});
- Using with specific elements:
$('img.adaptive-bg').adaptiveBackground({
parent: '.container'
});
- Customizing color selection:
$('img.adaptive-bg').adaptiveBackground({
selector: 'img',
exclude: [ 'rgb(0,0,0)', 'rgb(255,255,255)' ],
lightness: 0.4
});
Getting Started
- Include jQuery and the plugin in your HTML:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="path/to/jquery.adaptive-backgrounds.js"></script>
- Add the
data-adaptive-background
attribute to your images:
<img src="path/to/image.jpg" data-adaptive-background>
- Initialize the plugin:
$(document).ready(function(){
$.adaptiveBackground.run()
});
Competitor Comparisons
Grab the color palette from an image using just Javascript. Works in the browser and in Node.
Pros of Color Thief
- Language-agnostic: Implemented in JavaScript but can be used with any programming language
- More versatile: Can extract multiple dominant colors and color palettes
- Lightweight: No dependencies, making it easier to integrate into projects
Cons of Color Thief
- Manual implementation: Requires more code to apply extracted colors to elements
- Less automatic: Doesn't automatically adapt backgrounds without additional code
Code Comparison
Color Thief:
const colorThief = new ColorThief();
const color = colorThief.getColor(imageElement);
element.style.backgroundColor = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
jquery.adaptive-backgrounds.js:
$.adaptiveBackground.run({
selector: '.adapt',
parent: '.container'
});
Color Thief requires manual color application, while jquery.adaptive-backgrounds.js automatically adapts backgrounds with minimal setup. However, Color Thief offers more flexibility in color extraction and usage.
Both libraries serve similar purposes but cater to different use cases. Color Thief is better suited for projects requiring more control over color extraction and application, while jquery.adaptive-backgrounds.js is ideal for quick implementation of adaptive backgrounds with less customization.
Fast, small color manipulation and conversion for JavaScript
Pros of TinyColor
- More versatile color manipulation library, not limited to background adaptation
- Lightweight and dependency-free, can be used in various JavaScript environments
- Extensive color conversion and manipulation functions
Cons of TinyColor
- Doesn't provide automatic background color adaptation functionality
- Requires more manual implementation for specific use cases like adaptive backgrounds
Code Comparison
TinyColor:
var color = tinycolor("red");
var lighterColor = color.lighten(20);
var complementaryColor = color.complement();
jquery.adaptive-backgrounds.js:
$.adaptiveBackground.run({
parent: '.my-container',
normalizeTextColor: true,
lumaClasses: { light: "ab-light", dark: "ab-dark" }
});
Summary
TinyColor is a comprehensive color manipulation library, offering a wide range of color-related functions. It's more flexible and can be used in various scenarios beyond just adaptive backgrounds. However, it requires more manual implementation for specific use cases.
jquery.adaptive-backgrounds.js is specifically designed for adapting background colors based on image content, providing an easier out-of-the-box solution for this particular use case. It's more limited in scope but offers a simpler implementation for adaptive backgrounds.
Choose TinyColor for broader color manipulation needs, and jquery.adaptive-backgrounds.js for quick and easy adaptive background implementations.
Extract prominent colors from an image. JS port of Android's Palette.
Pros of vibrant.js
- Pure JavaScript implementation, no jQuery dependency
- Extracts multiple color swatches from images, not just a single background color
- Supports both browser and Node.js environments
Cons of vibrant.js
- More complex API, requiring more setup code
- Potentially slower performance due to more detailed color analysis
- Larger file size compared to the lightweight jquery.adaptive-backgrounds.js
Code Comparison
vibrant.js:
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches();
for (var swatch in swatches) {
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
console.log(swatch, swatches[swatch].getHex());
}
}
jquery.adaptive-backgrounds.js:
$('img.my-image').adaptiveBackground({
parent: '.my-container'
});
The code comparison shows that vibrant.js requires more setup and iteration to access color data, while jquery.adaptive-backgrounds.js offers a simpler, more declarative API. However, vibrant.js provides access to multiple color swatches, offering more flexibility for advanced use cases.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
jquery.adaptive-backgrounds.js
A simple jQuery plugin to extract the dominant color of an image and apply it to the background of its parent element.
Getting Started
Install via bower:
bower install --save adaptive.background
Then simply include jQuery and the script in your page, and invoke it like so:
$(document).ready(function(){
$.adaptiveBackground.run();
});
The script looks for image(s) with the data-adaptive-background
attribute:
<img src="/image.jpg" data-adaptive-background>
Using an element with a CSS background image
Instead of using an <img>
element nested inside of parent element, AB supports grabbing the dominant color of a background image of a standalone element, then applying the corresponding dominant color as the background color of said element.
Enable this functionality by adding a data property, data-ab-css-background
to the element. See the example below:
<div style='background-image: url(/some-image.jpg)' data-adaptive-background data-ab-css-background></div>
Demo
Here's a little demo of how it works. (1) The page loads (2) the dominant background color of the image is extracted (3) said color is applied to parent of image. Demo drastically slowed down to show effect.

API
This plugin exposes one method:
- $.adaptiveBackground.run(opts) arg: opts (Object) an optional argument to be merged in with the defaults.
Default Options
- selector String (default:
'img[data-adaptive-background="1"]'
) a CSS selector which denotes which images to grab/process. Ideally, this selector would start with img, to ensure we only grab and try to process actual images. - parent falsy (default:
null
) a CSS selector which denotes which parent to apply the background color to. By default, the color is applied to the parent one level up the DOM tree. - normalizeTextColor boolean (default:
false
) option to normalize the color of the parent text if background color is too dark or too light. - normalizedTextColors Object Literal (default:
{dark: '#000', light: '#fff'}
) text colors used when background is either too dark/light. - shadeVariation
blend|true|false
(default) option to shade the color of the parent ligher or darker (see shadePercentage) or blend the color of the parent with another color by a certain percentage (see shadeColors). - shadePercentage float (default:
0
) sets the percentage of shading or blending used. Can be adjusted from -1.00 to 1.00. - shadeColors Object Literal ( default:
{light:'rgb(255,255,255)',dark:'rgb(0,0,0)'}
) sets the color that will be used to blend the background color with. Two values are provided to account for the background color to be light or dark to start with. - transparent Transparent dominant color. Can be adjusted from 0.01 to 0.99.
Example:
Call the run
method, passing in any options you'd like to override.
var defaults = {
selector: '[data-adaptive-background="1"]',
parent: null,
exclude: [ 'rgb(0,0,0)', 'rgba(255,255,255)' ],
shadeVariation: false,
shadePercentage: 0,
shadeColors: {
light: 'rgb(255,255,255)',
dark: 'rgb(0,0,0)'
},
normalizeTextColor: false,
normalizedTextColors: {
light: "#fff",
dark: "#000"
},
lumaClasses: {
light: "ab-light",
dark: "ab-dark"
},
transparent: null
};
$.adaptiveBackground.run(defaults)
Events Emitted
- ab-color-found Event This event is fired when the dominant color of the image is found. The payload includes the dominant color as well as the color palette contained in the image.
Example:
Bind to the ab-color-found
event like so:
$('img.my-image').on('ab-color-found', function(ev,payload){
console.log(payload.color); // The dominant color in the image.
console.log(payload.palette); // The color palette found in the image.
console.log(ev); // The jQuery.Event object
});
Success Callback
You may wish to supply a callback function which is called once the magic has been performed.
$.adaptiveBackground.run({
success: function($img, data) {
console.log('Success!', $img, data);
}
});
Note, this callback is called once for each image.
Caveats
This plugin utlizes the <canvas>
element and the ImageData
object, and due to cross-site security limitations, the script will fail if one tries to extract the colors from an image not hosted on the current domain, unless the image allows for Cross Origin Resource Sharing.
Enabling CORS on S3
To enable CORS for images hosted on S3 buckets, follow the Amazon guide here; adding the following to the bucket's CORS configuration:
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
For all images, you can optionally also include a cross-origin attribute in your image. This is not absolutely necessary since the anonymous
origin is set in the Javascript code, but kudos to you for being a super-developer.
<img src="/image.jpg" data-adaptive-background cross-origin="anonymous"/>
Credit
This plugin is built on top of a script called RGBaster.
Collaborators
Brian Gonzalez | Scott Stern | Alfred J Kwack |
This project exists thanks to all the people who contribute. [Contribute].
Backers
Thank you to all our backers! ð [Become a backer]
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
License
MIT, yo.
Top Related Projects
Grab the color palette from an image using just Javascript. Works in the browser and in Node.
Fast, small color manipulation and conversion for JavaScript
Extract prominent colors from an image. JS port of Android's Palette.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot