Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change element styles via custom properties?

Tags:

css

polymer

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?

like image 938
kbwatts Avatar asked Apr 09 '26 10:04

kbwatts


2 Answers

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>
like image 164
kbwatts Avatar answered Apr 11 '26 00:04

kbwatts


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

like image 34
mmm111mmm Avatar answered Apr 11 '26 01:04

mmm111mmm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!