Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a different color for each tag

I have a select2 where the users can select tags from a list or add new tags. WHen the user insert a new tag, I record it on a database. The user can, from other screen edit this tag and associate it to a color. So my "tag" objects are like this:

{id:1, text:"cool tag", color:"#336699"}

What I would like to do is to show the tags with its colors inside the select2. I tried to do

formatSelection: function (tag) {
    return '<div style="background-color:'+tag.color+'">' + tag.text + '</div>';
},

but this does not change the background color of the div that holds the tag itself.

I also know I can use formatSelectionCssClass to add a css class to each item but in this case since the colors are user created, I do not have css classes with them (although if its the only way possible, is what I will do, dinamically generate a css file).

(PS.: This looks like a solution but I was looking for something more elegant)

like image 651
Leo Avatar asked Jul 28 '14 11:07

Leo


People also ask

Can you change tag color in HTML?

This is a newly added tag and introduced in HTML5. In most of the browser, the text contained with <mark> tag renders with the yellow background, but it can be changed using CSS background-color property.

How do I change text tag color?

To set the font color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property color. HTML5 do not support the <font> tag, so the CSS style is used to add font color.

How do you give text multiple colors in HTML?

Steps to add multicolor into text: Add a simple text inside the <div> tag with the required selector. Apply the linear gradient property with any colors of your choice. Apply webkit properties that will fill the text with the gradient background and declare the color property with transparent background.


1 Answers

Ok, I found a way to do this:

data = function(){
  return [{id:1, text:"tag 1", color:"#555555"}, {id:2, text:"tag 2", color:"#336699"}]
},

formatSelectionCssClass = function(tag, container) {
    $(container).parent().css({ "background-color": tag.color });
};
like image 158
Leo Avatar answered Oct 16 '22 10:10

Leo