3

I have the color theme of a website I'm working on change on refresh and would like to display the css background color attribute in my HTML. Is that possible?

i.e.

<footer>The color of the moment is <insert the background color attribute>. Refresh for a makeover</footer>

would display something like

"The color of the moment is #DB0C0C. Refresh for a makeover"

Since the hex color changes based on the style sheet loaded, I don't want to hardcode it. If I had a ruby variable @color which = #ff0000 and wanted to display it in html I could do something like

<%= @color%>

I'm wondering if there is any way to do something similar to access a CSS attribute.

2
  • Is there some reason you can't just write it in? Commented Apr 16, 2013 at 6:16
  • 2
    Then based on your edit, what you need is javascript. There is no pure css/html way to get that value otherwise. Commented Apr 16, 2013 at 7:23

2 Answers 2

2

You don't even need jQuery for this.. you can use just vanilla javascript with .getComputedStyle():

<span id='color-map'></span>

var element = document.getElementById("id-goes-here");
var style = window.getComputedStyle(element);

document.getElementById('color-map').innerHTML = style.backgroundColor;

However, it would appear that this does not give the color as a hex, but rather an 'rpg(x, y, z)' string. To get the hex from that, you can parse it using regex and return the result:

function rgbsToHex(str) {
    var hex = "#";
    var matches = str.match(/rgb\((\d+),\s(\d+),\s(\d+)\)/);
    hex += Number(matches[1]).toString(16);
    hex += Number(matches[2]).toString(16);
    hex += Number(matches[3]).toString(16);
    return hex;
}

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the .css() function in jQuery.

$('footer').find('span').text($('.bg').css('background-color'));

This will give you the color in rgb, if you would like to show it in HEX then check this for more info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.