skip to Main Content

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


  1. To add or remove a CSS file dynamically using JavaScript, you can use the following approach:

    1. Create a link element for the CSS file:
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = "path/to/your/css/file.css";
    
    1. To add the CSS file to the document, append the link element to the head element:
    document.head.appendChild(link);
    
    1. To remove the CSS file, remove the link element from the head element:
    document.head.removeChild(link);
    

    Here’s an example function that toggles the CSS file:

    function toggleCSS() {
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.type = "text/css";
      link.href = "path/to/your/css/file.css";
    
      var head = document.head;
      var existingLink = head.querySelector("link[rel='stylesheet']");
    
      if (existingLink) {
        head.removeChild(existingLink);
      } else {
        head.appendChild(link);
      }
    }
    

    When you call this function, it will toggle the CSS file on and off each time it’s called.

    Login or Signup to reply.
  2. 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 its disabled attribute.

    var styleElement = document.getElementById('toggled-style');
    
    function toggleStyle() {
      styleElement.disabled = !styleElement.disabled;
    }
    <head>
      <style id="always-active">
        /* All your regular CSS */
        
        body {
          background-color: CornSilk;
          color: CornflowerBlue;
        }
      </style>
    
      <style id="toggled-style">
        /* Style en/disabled by event trigger */
    
        /*
           These rules override any defined rules in 'always-active'
           when 'toggles-style' is not disabled.
        */
        body {
          background-color: CornflowerBlue;
          color: CornSilk;
        }
      </style>
    </head>
    
    <body>
      <p>some content</p>
      <button onclick="toggleStyle()">toggle</button>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search