4
votes

I'm trying to dynamically assign styles to my elements (in this case, a ExtJS displayfield).

I can't use CSS classes since I don't know what the colors will be until runtime.

I'm trying:

myDisplayField.getEl().applyStyles({ color: '#ff0000' });  //fail
myDisplayField.getEl().setStyle('color', '#ff0000');       //fail

Just to get the mechanism right, but neither seem to work.

It works using Ext.get(<div id>).setStyle(...), but that doesn't seem as clean to me. Is there a reason the former attempts don't work?

What am I missing? Thanks.

1

1 Answers

6
votes

The reason is simple: you're trying to set the styles on a wrong element. Each field, including displayfield, has quite complex table-based DOM structure that encapsulates the field label, the actual input element (or a div for display fields), and the supporting elements. field.getEl() returns the top, or main, element for a component; in this case that's the top <table> tag. What you need is the input element instead.

Now if you take a look at the DOM structure you'll notice that the <div> that you need to set styles on has an id of displayfield-123-inputEl. The -inputEl suffix is there for a reason; in most cases it indicates that the element has a Ext.dom.Element shortcut in its respective Component. For a field, that would be field.inputEl property that is available after the field has been rendered to the DOM. You can use that as well:

myDisplayField.inputEl.setStyle(...)

Or just use the convenience method available for the fields:

myDisplayField.setFieldStyle(...)

I would also suggest not hardcoding the colors but rather use CSS classes instead. In most cases there is a limited choice of colors depending on a condition, like invalid input, etc. Using CSS will require a bit more work upfront but will save you a lot of headache down the road, when someone will come up with a bright idea of changing the shade of red used for the invalid input, or somesuch.