Im looking for a smart way to change the background color for a page, but taking the #xxxxxx value from the dominant color of the headline picture.
In twenty eleven theme, I can set a random image for each page loaded, I would change the background color to match the picture.
I know that’s possible but I don’t know how to modify the CSS or the template to take the value from a specific function (I found this that seems promising:
https://stackoverflow.com/questions/2541481/get-average-color-of-image-via-javascript
Is that too complicated?
thanks alot
You can use a jQuery plugin called Color Thief.
Files needed:
WordPress setup:
Open
functions.php
(located in your theme’s folder) and add the code below to load the files in WordPress. In this case I placed all files in the “js” folder.As you can see I also created a
main.js
file to store the code that will run the color-thief code.main.js code:
The code above will look for an image with
id = target
.The
load()
function will ensure that the image has already loaded before the code is executed.Next the value of the dominant color is stored in a variable (the value returned is 3 numbers, which form the RGB color)
We use that same variable to change the color of the background.
The HTML setup:
The TwentyEleven theme loads the image through a function in the file
header.php
, but you can still edit the image tag and add an image ID to be able to find it easily with jQuery.In this case my image ID is
target
:And that should do it. Once the page loads, the jQuery script will look for an image with
id = target
. Get the dominant color of that image, and then apply it to the background of the page automatically.You can see a demo of this working here. (refresh the page a few times to until it loads a different image)