kbwatts
kbwatts

Reputation: 41

Dynamically change element styles via custom properties?

For example, you can change the ink colour in paper-tabs by changing --paper-tab-ink: var(--accent-color);. Is it possible to change the value of the CSS custom properties dynamically similar to how you can toggle a class or change the style in JS?

Upvotes: 3

Views: 1099

Answers (2)

mmm111mmm
mmm111mmm

Reputation: 4085

Yes, first get the object of your custom element. Then get the customStyle object. Add a style to that object. And then run element.updateStyles();

       t.clickListener= function(e) {
           var t = Polymer.dom(e).localTarget; //retarget if needed
           t.customStyle['--the-color-etc'] = 'pink';
           t.updateStyles(); // mandatory for the CSS variables shim
       };

See the docs

Upvotes: 1

kbwatts
kbwatts

Reputation: 41

There are different ways to do this, but a simple answer is to use the Polymer.updateStyles() method after making your class changes.

For example, let's say your styles are:

<style>
.yellow x-example {
  --light-primary-color: #fdd85f;
}
.red x-example {
  --light-primary-color: red;
}
</style>

and you want to make the component use the styles in the .red class. You simply add it as you normally would in javascript, then be sure to also use this function to actually update it on the page.

<div class="yellow" onclick="this.className='red'; Polymer.updateStyles()">
  <x-example></x-example>
</div>

Upvotes: 1

Related Questions