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...

2 Answers 2

8

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

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.