user2413035
user2413035

Reputation:

Set background color based on the value of a data attribute

I have 16 different section-tags. Every section-tag has a data- attribute to set a specific background-color for each section:

<section data-color="#A3D1B5">

Now I want to set this color as the background.

What I've already tried:
In CSS values using HTML5 data attribute, the answer says it should be possible to set the color like background: attr(data-color);, but this won't work for me.

I took a look at jQuery data() but I don't know how to set the background for all of the section-tags.

Are there any other solutions to handle this with jQuery's .data()?

Upvotes: 7

Views: 14644

Answers (4)

A. Wolff
A. Wolff

Reputation: 74420

DEMO

$("section").css('background', function () { //or for code's consistency, i'd use background-color instead
    return $(this).data('color')
});

Upvotes: 8

Aditya Singh
Aditya Singh

Reputation: 9612

Try this out:- http://jsfiddle.net/adiioo7/JgfkY/

JS:-

jQuery(function($){
    $("#section").css("background-color",$("#section").attr("data-color"));
});

HTML:-

<section id="section" data-color="#A3D1B5">Section with custom color</section>

Upvotes: 0

Alvaro
Alvaro

Reputation: 41595

You have to get the data-color attribute and assign it to the background in the css:

$('section').each(function(){
    $(this).css('background', $(this).attr('data-color'));
});

Living example: http://jsfiddle.net/Pk5dK/

Upvotes: 3

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

Try this code,

$("section").each(function(){
    $(this).css('background',$(this).data('color'));
});

http://jsfiddle.net/ZcPYv/

Upvotes: 3

Related Questions