jQuery plugin for color manipulation and animation support.

Overview

Build Status

jQuery Color

Supported jQuery versions: 1.8+

Browser Support

jQuery Color 3.x supports the following browsers:

Desktop:

  • Chrome: (Current - 1) and Current
  • Edge: (Current - 1) and Current, 18
  • Firefox: (Current - 1) and Current, ESR
  • Internet Explorer: 9+
  • Safari: (Current - 1) and Current
  • Opera: Current

Mobile:

  • Chrome on Android: (Current - 1) and Current
  • Safari on iOS: (Current - 2), (Current - 1) and Current

Information on browser support of jQuery Color 2.x can be found in the Browser Support section in its README.

Using jQuery Color in Production

We release jQuery Color by itself, or in a bundle. The extended names can be included as a jQuery Color plugin, or you can download the version of jQuery Color that includes the names. Choose your build from the following list:

Current version: 2.1.2

How to build and test jQuery Color

First, get a copy of the git repo by running:

git clone git://github.com/jquery/jquery-color.git

Enter the directory and install the node dependencies:

cd jquery-color && npm install

Make sure you have grunt installed by testing:

grunt -version

If not, run:

npm install -g grunt

To run tests locally, run grunt, and this will run the tests in PhantomJS.

You can also run the tests in a browser by navigating to the test/ directory.

Animated colors

This plugins installs a cssHook which allows jQuery's .animate() to animate between two colors.

Supported properties

backgroundColor, borderBottomColor, borderLeftColor, borderRightColor, borderTopColor, color, columnRuleColor, outlineColor, textDecorationColor, textEmphasisColor

Example use

<!DOCTYPE html>
<html>
<head>
<style>
div {
	background-color: #bada55;
	width: 100px;
	border: 1px solid green;
}
</style>
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="jquery.color.min.js"></script>
</head>
<body>
<button id="go">Simple</button>
<button id="sat">Desaturate</button>
<div id="block">Hello!</div>
<script>
$( "#go" ).on( "click", function() {
	$( "#block" ).animate( {
		backgroundColor: "#abcdef"
	}, 1500 );
});
$( "#sat" ).on( "click", function() {
	$( "#block" ).animate( {
		backgroundColor: jQuery.Color({ saturation: 0 })
	}, 1500 );
});
</script>
</body>
</html>

Supporting other properties

The jQuery.Color.hook() function can be called to support additional css properties as colors, and allow them to be animated.

Example use

// we want to animate SVG fill and stroke properties
jQuery.Color.hook( "fill stroke" );

The jQuery.Color Factory

The jQuery.Color() function allows you to create and manipulate color objects that are accepted by jQuery's .animate() and .css() functions.

  • Returns a new Color object, similar to jQuery() or jQuery.Event
  • Accepts many formats to create a new Color object with a jQuery.Color.fn prototype

Example uses:

// Parsing String Colors:
jQuery.Color( "#abcdef" );
jQuery.Color( "rgb(100, 200, 255)" );
jQuery.Color( "rgba(100, 200, 255, 0.5)" );
jQuery.Color( "aqua" );

// Creating Color Objects in Code:
// use null or undefined for values you wish to leave out
jQuery.Color( red, green, blue, alpha );
jQuery.Color([ red, green, blue, alpha ]);
jQuery.Color({ red: red, green: green, blue: blue, alpha: alpha });
jQuery.Color({ hue: hue, saturation: saturation, lightness: lightness, alpha: alpha });

// Helper to get value from CSS
jQuery.Color( element, cssProperty );

jQuery.Color.fn / prototype / the Color Object methods

Getters / Setters:

red()             // returns the "red" component of the color ( Integer from 0 - 255 )
red( val )        // returns a copy of the color object with the red set to val
green()           // returns the "green" component of the color from ( Integer from 0 - 255 )
green( val )      // returns a copy of the color object with the green set to val
blue()            // returns the "blue" component of the color from ( Integer from 0 - 255 )
blue( val )       // returns a copy of the color object with the blue set to val
alpha()           // returns the "alpha" component of the color from ( Float from 0.0 - 1.0 )
alpha( val )      // returns a copy of the color object with the alpha set to val
hue()             // returns the "hue" component of the color ( Integer from 0 - 359 )
hue( val )        // returns a copy of the color object with the hue set to val
saturation()      // returns the "saturation" component of the color ( Float from 0.0 - 1.0 )
saturation( val ) // returns a copy of the color object with the saturation set to val
lightness()       // returns the "lightness" component of the color ( Float from 0.0 - 1.0 )
lightness( val )  // returns a copy of the color object with the lightness set to val
// all of the above values can also take strings in the format of "+=100" or "-=100"

rgba() // returns a rgba "tuple" [ red, green, blue, alpha ]
// rgba() setters: returns a copy of the color with any defined values set to the new value
rgba( red, green, blue, alpha )
rgba( { red: red, green: green, blue: blue, alpha: alpha } )
rgba( [ red, green, blue, alpha ] )

hsla() // returns a HSL tuple [ hue, saturation, lightness, alpha ]
// much like the rgb setter - returns a copy with any defined values set
hsla( hue, saturation, lightness, alpha )
hsla( { hue: hue, saturation: saturation, lightness: lightness, alpha: alpha } )
hsla( [ hue, saturation, lightness, alpha ] )

String methods

toRgbaString() // returns a css string "rgba(255, 255, 255, 0.4)"
toHslaString() // returns a css string "hsla(330, 75%, 25%, 0.4)"
toHexString( includeAlpha ) // returns a css string "#abcdef", with "includeAlpha" uses "#rrggbbaa" (alpha *= 255)

The toRgbaString and toHslaString methods will only include the alpha channel if it is not 1. They will return rgb(...) and hsl(...) strings if the alpha is set to 1.

Working with other colors:

transition( othercolor, distance ) // the color distance ( 0.0 - 1.0 ) of the way between this color and othercolor
blend( othercolor ) // Will apply this color on top of the other color using alpha blending
is( othercolor ) // Will determine if this color is equal to all defined properties of othercolor

jQuery.Color properties

Internals on The Color Object

  • Internally, RGBA values are stored as color._rgba[0] = red, color._rgba[1] = green, color._rgba[2] = blue, color._rgba[3] = alpha. However, please remember there are nice convenient setters and getters for each of these properties.
  • undefined/null values for colors indicate non-existence. This signals the transition() function to keep whatever value was set in the other end of the transition. For example, animating to jQuery.Color([ 255, null, null, 1 ]) would only animate the red and alpha values of the color.

jQuery.Color.names

A list of named colors is stored on the jQuery.Color.names object. The value they contain should be parseable by jQuery.Color(). All names on this object should be lowercased. I.E. jQuery.Color("Red") is the same as doing jQuery.Color( jQuery.Color.names["red"] );

There is also a named color "_default" which by default is white, this is used for situations where a color is unparseable.

"transparent"

A special note about the color "transparent" - It returns null for red green and blue unless you specify colors for these values.

jQuery.Color( "#abcdef" ).transition( "transparent", 0.5 )

Animating to or from the value "transparent" will still use "#abcdef" for red green and blue.

HSLA Support

If a color is created using any of the HSLA functions or parsers, it will keep the _rgba array up to date as well as having a _hsla array. Once an RGBA operation is performed on HSLA, however, the _hsla cache is removed and all operations will continue based off of rgb (unless you go back into HSLA). The ._hsla array follows the same format as ._rbga, [hue, saturation, lightness, alpha ]. If you need to build an HSLA color from an HSLA array, jQuery.Color().hsla( array ) works for that purpose.

Colors with 0 saturation, or 100%/0% lightness will be stored with a hue of 0

Extensibility

It is possible for you to add your own functions to the color object. For instance, this function will tell you if its better to use black or white on a given background color.

// method taken from https://gist.github.com/960189
jQuery.Color.fn.contrastColor = function() {
	var r = this._rgba[ 0 ], g = this._rgba[ 1 ], b = this._rgba[ 2 ];
	return ( ( ( r * 299 ) + ( g * 587 ) + ( b * 144 ) ) / 1000 ) >= 131.5 ? "black" : "white";
};

// usage examples:
jQuery.Color( "#bada55" ).contrastColor(); // "black"
element.css( "color", jQuery.Color( element, "backgroundColor" ).contrastColor() );
Comments
  • update npm package

    update npm package

    I've noticed that npm thinks that jquery-color package is still v1.0.0 and that it depends on jQuery package (contrary to what package.json currently says).

    Can you npm publish newer version(s) of the package?

    build 
    opened by Mithgol 26
  • Wrapping style breaks AMD inclusion when built into other projects

    Wrapping style breaks AMD inclusion when built into other projects

    (This is a bit of a complicated one so thanks for bearing with me.)

    The tl;dr: of this is that as of jQuery UI 1.11 all modules support loading with AMD loaders like RequireJS. Referring to this by the name jQuery breaks the way jQuery conforms to AMD and you should change the last line of your built source to reflect the convention .

    The reason for this is because they wrap the entire build jquery-ui.js file in the following:

    (function( factory ) {
        if ( typeof define === "function" && define.amd ) {
            // AMD. Register as an anonymous module.
            define([ "jquery" ], factory );
        } else {
            // Browser globals
            factory( jQuery );
        }
    }(function( $ ) {
    [...]
    }));
    

    So, every module loaded has access to the top level jQuery object $ and they all operate on it by doing $.thing(. This project appears to break the convention by referring to jquery by its exported name jQuery here: https://github.com/jquery/jquery-color/blob/master/jquery.color.js#L663

    Perhaps there is a reason for this, but it causes problems with AMD loading as I will explain below. The easiest fix is to change jQuery in line 663 to $.

    If you're interested in the gorier details (and why I think this works for most people) they are as follows:

    I am including jquery-ui with RequireJS. jQueryUI obviously requires jQuery as a dependency. This is achieved by adding the following to your require config:

        shim: {
            'jquery-ui' : { exports: '$', deps: ['jquery'] },
            'jquery': { exports: '$' }
        },
    

    This tells require that it should load jquery before jquery-ui and pass the exported object ($1) as an invocation parameter to jQuery UI. (Hence the }(function( $ ) { in the top snippet.) This allows us to keep jQuery AND jQuery-UI completely out of the global namespace achieving true modularity. The reason I think this works is that the default build of jQuery includes this file: https://github.com/jquery/jquery/blob/master/src/exports/global.js which installs it in (and clobbers) the global namespace as $ and jQuery. However I and other make builds that don't include the global module using the supported custom argument to grunt when making jQuery. ( Reference: https://github.com/jquery/jquery/blob/master/README.md#custom-build-examples ) This produces a build of jquery that does nothing unless executed in the presence of an AMD loader ( reference: https://github.com/jquery/jquery/blob/master/src/exports/amd.js ) for maximum conformance.

    Thanks for reading a lot of words about why you should change six characters to one character in your source =)

    opened by ixtli 13
  • JQuery dependency

    JQuery dependency

    The library uses the 'JQuery' package and causes conflict with other libraries that use the correct case package 'jquery'. Also I'm having a bad time implementing easeing (ease In), does this plugin support easing?

    Thanks!

    opened by CaballoCarpiano 12
  • .toRgbString() returns unexpectedly unspaced result

    .toRgbString() returns unexpectedly unspaced result

    Dear Developers,

    color.toRgbString() is supposed to be compatible with the jQuery.css(), however it does not return an easily comparable value. In fact, jQuery.css("color") returns colors as "rgb(xxx, xxx, xxx)" while .toRgbString() return the same as "rgb(xxx,xxx,xxx)" without spaces! This makes impossible to easily compare colors as strings without workarounds such as $("<div>").css("color", color.toRgbString()).css("color"). This is especially important when comparing miscellaneous CSS proprieties.

    Example code where I needed to use the workaround to make things work seamlessly:

    $("#element").click(function() {
    $(this).animate(
    {
       "backgroundColor": "red",
       "width", "+=100"
    }, {
        duration: 1000,
        step(val, fx) {
        // some code here
        if( $("<div>").css(fx.prop, fx.end.toString()).css(fx.prop) == check[fx.prop]) { ... }
        /* instead of the expected: 
         * if(fx.end.toString() == check[fx.prop]) { ... }
         */
        // more code here
        }
    })
    });
    

    It would be great if this little bug could be fixed. Thank you for your great work, Warmest Regards.

    opened by jhack89 9
  • Update npm package jquery-color

    Update npm package jquery-color

    Could you kindly update your npm package jquery-color?

    It still mentions v1.0.0 and it has a single npm dependency for an old version of jquery, namely jquery v1.7.4 which is deprecated.

    Any reason why jquery-color doesn't work with the lastest version of jquery?

    I suppose you just need to do

    npm i jquery@">=1.11.0"
    npm version <new version>
    npm publish
    

    Furthermore in said npm package the link to github gives 404 page not found, when it should redirect here.

    opened by jfoclpf 8
  • Travis CI

    Travis CI

    Hi @gnarf, @leobalter I gave the kickoff for integration. I wonder if can enable jquery-color in travis.

    Currently the script only runs grunt, but I'll integrate it with browserstack later.

    build 
    opened by raphamorim 8
  • Reconsolidate with Wikimedia fork

    Reconsolidate with Wikimedia fork

    opened by Krinkle 7
  • Make the library compatible with NPM

    Make the library compatible with NPM

    NPM and other package managers like JSPM expect to have a main attribute in package.json to specify which file should be returned when someone requires the library. [1]

    It also needs a list of required runtime dependencies [2]

    This is related to #84

    build 
    opened by Gotusso 6
  • Cannot call method 'indexOf' of undefined

    Cannot call method 'indexOf' of undefined

    I can't build jquery-color. I have PhantomJS and grunt installed.

    grunt
    

    outputs this warning >>

    Running "compare_size" task
    <WARN> An error occurred while processing a template (Cannot call method 'indexOf' of undefined). Use --force to continue. </WARN>
    
    opened by daxxog 6
  • Add all 147 HTML/CSS legal color names into new SVG-names JS file

    Add all 147 HTML/CSS legal color names into new SVG-names JS file

    This is the replacement to Pull Request #29. (Though, I still think you guys are going overboard on the file reduction for a measly 1K of minified space. jQuery proper and jQuery UI, yeah. This tiny little plugin, not so much...)

    The new file is called jquery.color.svg-names.js, which contains the extended SVG color names. The original file has had all of the color names stripped except for the basic 16 colors + transparent and _default. This reduces the YUI compressed size to 2889 bytes vs. 3121 bytes. The downside is a break in backwards-compatibility. (Slight break; the user merely has to load the other file.)

    If this works for you guys, this request has the color stripping. Otherwise, the original file can be restored to retain 100% BC and 232 mini+gzip bytes.

    opened by SineSwiper 6
  • If set color via Hsla, Rgba is not set

    If set color via Hsla, Rgba is not set

    I set something like this. It doesn't store RGB as specified by the docs.

    col = $.Color
       hue: 240
       saturation: 1
       lightness: .5
    console.log col._rgba # Outputs [null, null, null, 1]
    console.log col.toHslaString # Outputs hsla(240, 100%, 50%, 1)
    
    opened by thevinci 6
  • Parse color from css vars ?

    Parse color from css vars ?

    is it possible to get the color object from css vars ? for example like this jQuery.Color( 'var(--heading-color)' ) or is there any method to extend to jQuery.Color to parse the css variable ?

    Thanks

    opened by resarahman 0
  • Update the svg-names addon code to also UMD

    Update the svg-names addon code to also UMD

    cc @raphamorim

    We've update the main jquery.color to be UMD and stuff with the #87 PR, but we still need to figure out how the svg-names and the "concatenated" version get released.

    opened by gnarf 1
  • Function to determine if a color parsed or used the default

    Function to determine if a color parsed or used the default

    var fixedDefaultString = "#abcdef";
    jQuery.Color.names["_default"] = fixedDefaultString;
    var defaultColor = jQuery.Color("_default");
    var parsedAsDefault = jQuery.Color("#abcdef");
    var unparsed = jQuery.Color("I AM THE KING POTATO");
    

    It would be nice to have a way to determine that unparsed is using the default, whereas parsedAsDefault is not. Ideally, it would be available after construction via something like .isParseable().

    I'm unclear on what isParseable() should return in cases that do not involve parsing a string, however. For example:

    jQuery.Color(100, 100, 100, 100).isParseable();
    jQuery.Color().isParseable();
    
    opened by ghost 1
  • Make the README into API docs

    Make the README into API docs

    I asked @kswedberg in IRC today to take a look at the readme here and help me add some prose/better documentation for these signatures. Currently it is pretty hard to actually learn about everything color can do since the language in the readme isn't very easy.

    opened by gnarf 5
Releases(3.0.0-alpha.2)
  • 3.0.0-alpha.2(May 11, 2020)

  • 2.2.0(May 11, 2020)

    More than 7 years since the release of jQuery Color 2.1.2, version 2.2.0 is out!

    Download jQuery Color via the jquery-color package on npm or Bower or get it from the CDN: https://code.jquery.com/color/.

    Browser support: README.md#browser-support.

    This release has been tested with jQuery versions from 1.5.2 to 3.5.1.

    Notable changes:

    • jQuery Color is being published to npm again (in addition to Bower)
    • Core: Add support for short hex colors with alpha transparency (2d1a90b)
    • Core: Add support for hex colors with alpha transparency (#129, be4c76d)
    • Core: Don't reset alpha to 1 if all red, green, blue & alpha provided (#58, 0fbc05e)
    • Core: Don't use the deprecated jQuery.type (#115, 406ec68)
    • Core: Add magenta to the extended names list (afcce6c)
    • Core: Add rebeccapurple to the extended names list (8e8e243)
    • Define AMD & CommonJS modules (bc15d71), (1046b6d), (cfbb17e)

    See the full changelog here.

    Thank you to all of you who participated in this release by submitting patches, reporting bugs, or testing, including Anne-Gaelle Colom, Corey Frang, Franco Gotusso, GitHub, Jörn Zaefferer, Leo Balter, Leonardo Balter, Michał Gołębiowski-Owczarek, Mike Sherov, Raphael Amorim, Rob Garrison, Ryan Jacobson, Scott González, Theron Luhn & Timo Tijhof.

    Source code(tar.gz)
    Source code(zip)
Owner
jQuery
jQuery
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A JavaScript animation plugin for menus. It creates a div that moves when you mouse over an element, giving it an elastic animation.

Lava-Lamp Description: A JavaScript animation plugin for menus. It creates a div that moves when you mouse over an element, giving it an elastic anima

Richard Hung 38 Jun 4, 2022
Tool Cool Color Picker is a color picker library written in typescript and using web component technologies.

Tool Cool Color Picker Tool Cool Color Picker is a color picker library written in typescript and using web component technologies. Check out the demo

Tool Cool 13 Oct 23, 2022
Change the color of an image to a specific color you have in mind.

image-recolor Run it: https://image-recolor.vercel.app/ image.recolor.mov Acknowledgments Daniel Büchele for the algorithm: https://twitter.com/daniel

Christopher Chedeau 21 Oct 25, 2022
A little toy app to help you find the nearest match for a given color within a Figma Tokens color palette.

Hey Palette So you've got a color palette in Figma and you've used the Figma Tokens plugin to export that palette to JSON. Let's say you have a color

Kalo Pilato 5 Nov 15, 2022
Colr Pickr, a vanilla JavaScript color picker component built with SVGs, with features like saving colors. Similar design to the chrome-dev-tools color picker.

Colr Pickr Colr Pickr, a vanilla JavaScript color picking component built with SVGs, with features like saving colors. Similar design to the chrome-de

TEK 27 Jun 27, 2022
A NodeJS package to convert any RGB color to HEX color or viceversa. Also supports HSL conversion.

Unhex ?? A NodeJS package to convert any RGB color to HEX, HSL color or viceversa. Example div { color: #fff; background-color: #0070f3; } After r

Arnau Espin 2 Oct 1, 2022
I made countdown birthday and fireworks animation using HTML Canvas, CSS, JS. The fireworks animation gonna come out once the countdown is finished or in other words, "Birthday Time".

Countdown-Birthday-Fireworks-Animation I made countdown birthday and fireworks animation using HTML Canvas, CSS, JS. The fireworks animation gonna com

Mahardika Bayu S.B 19 Dec 31, 2022
Animation library build on top of web animation API (WAAPI)

unanime.js Javascript animation library build on top of web animation API (WAAPI). Learn more about WAAPI: Web animation API Documentation Blog Daniel

Clément Laval 3 Jun 21, 2022
Query for CSS brower support data, combined from caniuse and MDN, including version support started and global support percentages.

css-browser-support Query for CSS browser support data, combined from caniuse and MDN, including version support started and global support percentage

Stephanie Eckles 65 Nov 2, 2022
A small javascript DOM manipulation library based on Jquery's syntax. Acts as a small utility library with the most common functions.

Quantdom JS Quantdom is a very small (about 600 bytes when ran through terser & gzipped) dom danipulation library that uuses a Jquery like syntax and

Sean McQuaid 7 Aug 16, 2022
Data Manipulation Form panel plugin for @grafana.

Data Manipulation Form panel plugin for Grafana Introduction The Data Manipulation Form Panel is a plugin for Grafana that can be used to insert, upda

Volkov Labs 25 Dec 28, 2022
Marker animation jQuery plugin

jQuery Marker Animation Read this in other languages: English, 日本語. jQuery plugin to add under line animation like highlighter. Demonstration Table of

Technote 12 Nov 8, 2022
An app to manage tasks. A user can add, delete and edit a task and mark it as completed, It uses simple GUI and relies on DOM manipulation in pure JS and using local storage.

An app to manage tasks. A user can add, delete and edit a task and mark it as completed, It uses simple GUI and relies on DOM manipulation in pure JS and using local storage.

KHITER Mohamed Achraf 6 Aug 20, 2022
Flat and simple color-picker library. No dependencies, no jquery.

Flat and simple color-picker Fully Featured demo Features Simple: The interface is straight forward and easy to use. Practical: Multiple color represe

Ivan Matveev 15 Nov 14, 2022
quASAR: ASAR manipulation made easy

quASAR quASAR: ASAR manipulation made easy This project is a proof-of-concept for manipulating ASAR files for code injection in Electron apps. This ca

Michael Taggart 19 Sep 25, 2022
jQuery UI widget for color picking (similar to the one in Microsoft Office 2010).

evol-colorpicker · evol-colorpicker is a web color picker which looks like the one in Microsoft Office 2010. It can be used inline or as a popup bound

Olivier Giulieri 285 Dec 14, 2022