Jquery - Adding and removing the style sheet at the click

advertisements

I've got an element set to append a style-sheet into the head via the following:

$(document).ready(function () {
    $(".css_switch").click(function () {
        $('head').append('<link rel="stylesheet" href="style2.css" />');
    });
});

It's working as required in terms of adding the style-sheet to the head and giving the required effect, however what I would like is that when you click .css_switch, it removes the style-sheet that I just added to the head, so it sort of turns it off and on.

Please note I don't want to disable the original style-sheet at all, as I am still using a large chunk of that.

Thanks.


You don't have to remove a stylesheet completely from DOM: just disable it. It's easy to do, actually, but there are two things to be aware of:

$(function() {
  var linkEl;
  $(".css_switch").click(function() {
    if (!linkEl) {
      linkEl = $('<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />')
                .appendTo('head')[0];
    }
    else if (linkEl.sheet) {
      linkEl.sheet.disabled = !linkEl.sheet.disabled;
    }
  });
});

Demo. Each style link element has associated StyleSheet object, which can be disabled with, quite unsurprisingly, disabled property. But there's a caveat: the aforementioned object is created only when the external CSS document is loaded and parsed. Until this, linkEl.sheet is null; hence the check.

Note that simpler version:

else { linkEl.disabled = !linkEl.disabled; }

... works too (you change property of corresponding HTMLLinkElement, disabling it instead), but there's a subtle bug: this property can be changed even when the resource is not ready. So imagine a user clicking on the button, seeing no changes afterwards (CSS isn't loaded yet). Now they click the button again, this time disabling the link - and when the resource is there, it's not shown. A user is dazed and confused, and that's usually not good.

With the quoted version, disabling is done only when a user sees the result of CSS change.