I'm trying to dynamically change the media attribute of a CSS link tag and I need to run a function after the new CSS is applied.
I have a CSS stylesheet link tag
<link href="print.css" rel="stylesheet" media="print">
Inside my JavaScript code, I want to change the media attribute from print to all, and after the new style changes are applied to my page, I need to run a function.
Right now, I'm doing the following:
if (myCSSlink.getAttribute("media") === "print") {
myCSSlink.setAttribute("media", "all");
myCSSlink.onload = () => {
//do some work
};
}
At this point, I'm assuming that after the media attribute is changed, the CSS loads again.
But my code inside the anonymous arrow function doesn't seem to work. How can I approach this?
You should assign an onload handler to do both - change the media attribute and run your custom onload function.
function onLoad(link) {
link.setAttribute('media', 'all');
yourCustomFunction();
}
<link href="print.css" rel="stylesheet" media="print" onload="onLoad(this);">