CSS by data-attribute will not refresh/repaint
Asked Answered
D

2

9

In a HTML5/JS application we have a view with some styles depending on the data-attribute of elements:

like

<li data-level="0"></li>

or

<li data-level="1"></li>

CSS

li[data-level^="1"] {
  /* some styles */
}

This seems to work just fine everywhere on page reload.

But when the data-attribute get set programmatically via JS, the CSS properties get rendered in all relevant desktop browsers, but not in mobile safari.

JS part looks like this:

this.$el.attr('data-level', this.model.getLevel())

Any ideas on how to force to apply those properties (refresh/repaint something) ?

I would like to avoid using the class attribute and different classes as things are more complex than shown here...

Debauch answered 31/7, 2013 at 9:59 Comment(0)
D
9

ok, changing data attributes simply doesn't seem to trigger a redraw of the element in all browsers !?

Changing the class attribute however does. Kind of a workaround, but does the trick.

this.$el
       .attr('data-level', this.model.getLevel())
       .addClass('force-repaint')
       .removeClass('force-repaint');

As seen here: Changing a data attribute in Safari, but the screen does not redraw to new CSS style

Debauch answered 1/8, 2013 at 6:38 Comment(0)
S
0

In my case, I was working with a font icon generated with icomoon and using the data attribute data-icon to change the HTML entity dynamically.

On page reload, it would work in tandem with this css:

[data-icon]:before {
    content: attr(data-icon);
}

But without reload, and even by changing classes, it didn't change, just displayed the code.

<span class="font-icon" data-icon="&#xe901;"></span>

What worked for me was using this function, which I edited to the following (assuming code in the shape of e901):

export class StringUtils {
  static emptyElement = document.createElement('div');
  static fontCodeToSymbol(code: string): string {
    let element = StringUtils.emptyElement;
    let symbol: string | nullable = `&#x${code};`;
    if (symbol && typeof symbol === 'string') {
      element.innerHTML = symbol;
      symbol = element.textContent;
      element.textContent = '';
    }
    return symbol || '';
  }
}

Which would directly feed the correct character in data-icon:

<span class="font-icon" data-icon=""></span>
Synthetic answered 17/5, 2018 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.