Search code examples
javascriptcssdomdom-events

Trying to enable and disable css files through javascript


I have 2 different css files, I want to use them both dynamically. I have a mobile preview button that will change to another css file, and also change the same button text to Desktop Preview, and I want the css to change to the original file. I only being able to change to the second file when pressing mobile preview, but after pressing the same button I get an error
"TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."

This is my code:

mobileBtn.addEventListener('click', () => {
    const mobileLink = document.createElement('link');
    mobileLink.rel = 'stylesheet';
    mobileLink.type = 'text/css';
    mobileLink.href = 'styles-no-media-query.css'
    document.head.appendChild(mobileLink);

    const currentStyleSheet = document.querySelector('link[href="styles2.css"]');
    const alternativeStyleSheet = document.querySelector('link[href="styles-no-media-query.css"]');

    if (currentStyleSheet) {
      currentStyleSheet.remove();
      document.head.appendChild(alternativeStyleSheet);
      btnText.textContent = 'Desktop Preview';
    } else {
      alternativeStyleSheet.remove();
      document.head.appendChild(currentStyleSheet);
      btnText.textContent = 'Mobile Preview';
    }
});

the currentStyleSheet returns null after pressing the button, could not figure out why. Tried to make the same as the mobileLink but as a desktopLink which did not work.

Would appreciate a bit of help here. Thanks!


Solution

  • Provided with your attempt to dynamically add a element in your click handler, I'd suggest, that you try another approach.

    Just have 1 element and change its attributes (mainly the href one, but other you may need to change other ones too) in the click handler.

    Add a link element in your document with an id='my-link-el'.

    Then you'll be able to get it and just check & change its href attribute (the example should work provided you have that btnTxt variable defined and holding an appropriate value):

    mobileBtn.addEventListener('click', () => {
      const linkEl = document.querySelector('#my-link-el');
      const currentStyleSheetHref = 'styles2.css';
      const alternativeStyleSheetHref = 'styles-no-media-query.css';
    
      if (linkEl.href.endsWith(currentStyleSheetHref)) {
        linkEl.href = alternativeStyleSheetHref;
        btnText.textContent = 'Desktop Preview';
      } else {
        linkEl.href = currentStyleSheetHref;
        btnText.textContent = 'Mobile Preview';
      }
    });