8

Trying to find code for switching between two style sheets with just one button. I've tried to adapt others' solutions, but to no avail (yet). Here's my most recent attempt:

Set Up:

<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<script type="text/javascript">
function toggle() {
    var el = document.getElementById("style1");
    if (el.href == "resumecss.css") {
        el.href = "resumecssinvert.css";    
    }
    else {
        el.href = "resumecss.css";  
    }
}
</script>

Calling:

<button type="button" onclick="toggle()">Switch</button>

The purpose being to flip between two skins on one page repeatably.

Thanks in advance to those of you kind/knowledgeable to help.

0

6 Answers 6

8

Try including both of them, and then switched the disabled flag

<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<link id="style2" rel="stylesheet" type="text/css" href="resumecssinvert.css" disabled="disabled" />
<script type="text/javascript">
  function toggle() {
    var el1 = document.getElementById("style1"),
        el2 = document.getElementById("style2");
    if (el1.disabled === "disabled") {
      el1.disabled = undefined;
      el2.disabled = "disabled";
    } else {
      el1.disabled = "disabled";
      el2.disabled = undefined;
    }
  }
</script>

Updated example using attribute methods:

const
  normalStyle   = document.getElementById('style1'),
  invertedStyle = document.getElementById('style2');

const toggle = (style1, style2) => {
  if (style1.hasAttribute('disabled')) {
    style1.removeAttribute('disabled');
    style2.setAttribute('disabled', '');
  } else {
    style1.setAttribute('disabled', '');
    style2.removeAttribute('disabled');
  }
}

toggle(normalStyle, invertedStyle); // Swap disabled flag
<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<link id="style2" rel="stylesheet" type="text/css" href="resumecssinvert.css" disabled />

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure how browser caching works, but this one may lead to a smoother user experience since it's loading both rulesets a single time, and at the very beginning.
5

This is the shortest solution I could think of (and works probably in all browsers):

function toggle() {
  var a = document.getElementById("style1");
  a.x = 'resumecssinvert' == a.x ? 'resumecss' : 'resumecssinvert'; // short if
  a.href = a.x + '.css';
}

As everything in javascript is a object you can simply add properties.

Assuming that your default css is "resumecss"

The first time x is not set and returns false, so "resumecssinvert" will be set.

The second time time x is set and returns true and switches back. Everything works as it should.

1 Comment

The only works once, once I click the button again, it stops working.
5

Your script is solid, except that the href attribute is a full URL, even if you use a relative path. Here's the code I used that works:

function toggle() {
    var el = document.getElementById("style1");
    if (el.href.match("resumecss.css")) {
        el.href = "resumecssinvert.css";    
    }
    else {
        el.href = "resumecss.css";  
    }
}

See fiddle here: http://jsfiddle.net/jakelauer/LWJjX/

1 Comment

+1, but please split JavaScript from the HTML next time: jsfiddle.net/LWJjX/3
1

Add both stylesheets to the page, click on the button to disable one and the other is automatically active

let button = document.getElementById("IdName")
button.addEventListener("click", () => {
  let stylesheet = document.getElementById("style1");
  stylesheet.toggleAttribute("disabled")
})

Comments

0

This one works with jQuery.

$('#dark-css').click(function() {
  var $darkCss = $("link[href='dark.css']");
  if ($darkCss.length) {
    $darkCss.remove();
  } else {
    $('head').append('<link type="text/css" rel="stylesheet" media="all" href="dark.css">');
  }
});

Updated example

(function($) {
  $.createStylesheet = function(href) {
    return $('<link>', {
      type: 'text/css',
      rel: 'stylesheet',
      media: 'all',
      href: href
    })
  };
})(jQuery);

$('#dark-css').click(function() {
  var $darkCss = $('link[href="dark.css"]');
  if ($darkCss.length) {
    $darkCss.remove();
    console.log('Removing dark theme...');
  } else {
    $('head').append($.createStylesheet('dark.css'));
    console.log('Loading dark theme...');
  }
});
.as-console-wrapper { max-height: 3rem !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" media="all" href="dark.css">
<h1>Hello World</h1>
<button type="button" id="dark-css">Toggle Dark Mode</button>

Comments

0

In the answer below, the stylesheets may be added preemptively, or lazy-loaded. They are located in the document by their href attribute value.

They can be loaded up-front, or loaded upon request. Once they are loaded, they can be enabled/disabled by toggling their disabled attribute. This way, the scripts are only every loaded one time.

const main = () => {
  const
    normalStyle   = getOrLoadStylesheet('resume.css'),
    invertedStyle = getOrLoadStylesheet('resume-inverted.css');

  toggleStylesheet(normalStyle, invertedStyle); // Swap disabled flag
};

const createElement = (tagName, config, target) => {
  const el = Object.assign(document.createElement(tagName), config);
  if (target) target.append(el);
  return el;
};

const createStylesheet = (href) =>
  createElement('link',
    { rel: 'stylesheet', type: 'text/css', disabled: 'disabled', href },
    document.head);

const getOrLoadStylesheet = (href) =>
  document.querySelector(`link[href="${href}"]`) ?? createStylesheet(href);

const toggleStylesheet = (style1, style2) => {
  if (style1.hasAttribute('disabled')) {
    style1.removeAttribute('disabled');
    style2.setAttribute('disabled', '');
  } else {
    style1.setAttribute('disabled', '');
    style2.removeAttribute('disabled');
  }
}

main();
<!--

<link rel="stylesheet" type="text/css" href="resume.css" />
<link rel="stylesheet" type="text/css" href="resume-inverted.css" disabled />

-->

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.