For an example I want JS to switch attached CSS files after some events (this events can’t be realized through css @media function)
How to make it most compact and easy way?
For an example I want JS to switch attached CSS files after some events (this events can’t be realized through css @media function)
How to make it most compact and easy way?
2
Answers
To add or remove a CSS file dynamically using JavaScript, you can use the following approach:
Here’s an example function that toggles the CSS file:
When you call this function, it will toggle the CSS file on and off each time it’s called.
When you only need to toggle a few CSS rules you can load all CSS and put the CSS that needs to be toggled/overridden in its own
<style>
block last in line in<head>
.Give the
<style>
to be toggled an ID or classname and simply toggle the styles’disabled
attribute.Below snippet contains a simple proof of concept. This Codepen shows an elaborate demo toggling all kinds of styles of a page.
BTW this also works for
<link rel="stylesheet" id="some-external-style" href="...">
. Simply get the reference in JS and toggle itsdisabled
attribute.