4

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 Answer 1

6

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.

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

3 Comments

To supplement your answer jsfiddle, as I alredy did, and my answer was late) jsfiddle.net/eC9j8
The colors arn't hardcoded - they just are in this code snippet; in my code they're calculated using a gradient. But I learnt a lot from this answer - greatly appreciate your taking the time to help out
but why would displayfield and label be so different to each other? displayfield is used in a form context but thats all. So it should be just as easy to modify stylisticly as a label... anyway seems strange to me.

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.