ExtJS Dynamically change button background color based on color selection

I have a Sencha ExtJS application where a user enters some data into an input form and then selects a color associated with that element. After clicking the save button on the form, the form closes and creates a button for the new item. I'm basically trying to figure out how to change the background color of a button to match what the user chooses. I did a bunch of searches and found that most do it with CSS and set the cls property. It would be nice if I split the line in the css file for each color in the picker, but there must be a way to dynamically set the background color of the button when the color is unknown.

layoutRoot.down('#pnlTest').add({ xtype: 'button', text: obj.name, height: 25, width: 125, margin: '5', });

      

+3


source to share


3 answers


It's a bit unwise to have a class for color! You should be able to manually set the style using the style attribute . Just replace the hex string with your variable.

{
    xtype: 'button', 
    text: obj.name, 
    height: 25, 
    width: 125, 
    margin: '5', 
    style: {
        background: '#FF5566'
    }
}

      



Relevant docs (docs for ExtJs version 5.0, but this feature is available since version 1.1.0) http://docs.sencha.com/extjs/5.0/apidocs/#!/api/Ext.Component-cfg-style

+4


source


Create an rgb string from your set of colors (the syntax here might change depending on how your picker returns the color)
var rgb = [picker.r, picker.g, picker.b];


var string = 'rgb(' + rgb.join(',') + ')'

Get a button using your ID

var button = Ext.getCmp('Your_button_ID');

      



Change button color

button.getEl().dom.style.background = string;

      

+3


source


Have you tried removeCls and then the addCls method defined for the button to change the color as needed?

Try the removeCls method to remove the existing CSS if any, and then set the background color you want to use in another css class and add that CSS class to the button using the addCls method.

+2


source







All Articles