I'm having difficulties with Internet Explorer (even as up-to-date as IE11). I'm trying to write some JavaScript that will allow me to dynamically create a style sheet, add it to the document and manipulate styles, most of which is based on the article that David Walsh wrote. He had the idea of setting the media
attribute of the created style
tag so legacy browsers will simply ignore rules that they can't support - an idea that I really like, but one that's causing me a few problems.
When I create a style
tag with a media
attribute more complicated than "screen"
, Firefox and Chrome will apply the new rules instantly (assuming the media query matches), but IE will not until some kind of page repaint is triggered (resizing the page seems the most effective).
I've created a fiddle to better demonstrate the issue. I'm seeing the results panel having a green background in Firefox and Chrome but red in IE until the repaint is forced. As for actually forcing a repaint, I've tried a few tricks to no success:
document.body.className = document.body.className;
element.appendChild(document.createTextNode(' '));
document.body.style.width = (previousWidth + 1) + 'px'
all and (min-width: 10px)
and even just (min-width: 10px)
My question is "How can I get IE to implement the styles when they're added?" (or at least, as close to the time their added a possible, I can live with a setTimeout
being needed)
I'm using jQuery on the site itself so I'll accept a jQuery answer, but I'd prefer one without a library dependancy so I better understand what's causing the issue and how to resolve it.
If you disable line 65 of the javascript it appears to work:
// Webkit hack.
// element.appendChild(document.createTextNode(''));
Since this is apparently a hack, perhaps it can be removed, or worked around more elegantly.
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With