Project 3: jQuery color picker
In class, I’ve been developing a simple color tool using jQuery. The latest code is in:
If you have previously cloned the
cs120pub folder, you can go to
that directory in your terminal and request it to download any
cd ~/Desktop/cs120pub git pull
But make sure you make any changes in your own
cs120 folder, not
Your task for this assignment is to extend the color selector as follows:
- Add the slider corresponding to the blue channel, and make sure it works.
- Make the rgb specification appear on the page itself, not just in the console.
- Provide a palette of several predefined colors. Here is how I
recommend starting it:
<div id="palette"> <div style="background:#000000"></div> <div style="background:#ffffff"></div> <div style="background:#c25a5a"></div> <div style="background:#c2c25a"></div> </div>
Then you can use CSS rules to make sure the child divs pile up left-to-right (float them to the left) and have a fixed width and height. The selector for that rule can be
div#palette > div.
- When our user clicks on a color in the palette, it loads that
predefined color into the swatch (the larger box), and the
sliders, and the
rgb(…)display. One trick I used for this is to use
.cssto grab the background color property (which conveniently is already in the
rgb(…)format) and then convert it from a string into a record containing the three components.
var rgb = getRGB($(this).css("background-color")) red = rgb.red green = rgb.green blue = rgb.blue
getRGBwas from this StackOverflow answer:
- Finally, when our user clicks on the swatch (the larger box), it
adds that color to the palette! To construct a brand new element
dynamically with jQuery, you can use syntax like this:
var elt = $("<div></div>") elt.css("background-color", …)
Unfortunately, it will not pick up the click handler specified for previously-existing elements, so you will need to specify the click handler separately:
And then you can add it to the end of a parent element using:
Below is a screenshot of my solution.